jquery addclass()怎么用

青灯夜游
青灯夜游原创
2022-03-01 16:05:402088浏览

在jquery中,addclass()方法用于向被选元素添加一个或多个类,语法为“$(selector).addClass(“类名”)”;如需添加多个类,需要使用空格分隔类名。

本教程操作环境:windows7系统、jquery1.10.2版本、Dell G3电脑。

在jquery中,addclass()方法用于向被选元素添加一个或多个类。

该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。

提示:如需添加多个类,请使用空格分隔类名。

语法

$(selector).addClass(class)

也使用函数向被选元素添加类

$(selector).addClass(function(index,oldclass))

1.png

示例:

向第一个 p 元素添加一个类

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					$("p:first").addClass("intro");
				});
			});
		</script>
		<style type="text/css">
			.intro {
				font-size: 120%;
				color: red;
			}
		</style>

	</head>

	<body>
		<h1>这是一个大标题</h1>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<button>向第一个 p 元素添加一个类</button>
	</body>

</html>

1.gif

向元素添加两个类

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					$("p:first").addClass("intro note");
				});
			});
		</script>
		<style type="text/css">
			.intro {
				font-size: 120%;
				color: blue;
			}

			.note {
				background-color: yellow;
			}
		</style>

	</head>

	<body>
		<h1>这是一个大标题</h1>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<button>向第一个 p 元素添加一个类</button>
	</body>

</html>

2.gif

【推荐学习:jQuery视频教程web前端

以上就是jquery addclass()怎么用的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。