.addClass()


.addClass( className )返回: jQuery

描述: 为每个匹配的元素添加指定的样式类名

  • 添加的版本: 1.0.addClass( className )

    • className
      类型: String
      为每个匹配元素所要增加的一个或多个样式名。
  • 添加的版本: 1.4.addClass( function(index, currentClass) )

    • function(index, currentClass)
      类型: Function()
      这个函数返回一个或更多用空格隔开的要增加的样式名。接收index 参数表示元素在匹配集合中的索引位置和html 参数表示元素上原来的 HTML 内容。在函数中this指向匹配元素集合中的当前元素。

值得注意的是这个方法不会替换一个样式类名。它只是简单的添加一个样式类名到元素上。

对所有匹配的元素可以一次添加多个用空格隔开的样式类名, 像这样:

1
$("p").addClass("myClass yourClass");

这个方法通常和.removeClass()一起使用,用来切换元素的样式, 像这样:

1
$("p").removeClass("myClass noClass").addClass("yourClass");

这里, myClassnoClass 样式名在所有段落上被移除, 然后 yourClass 被添加。

自 jQuery 1.4开始, .addClass() 方法允许我们通过传递一个用来设置样式类名的函数。

1
2
3
$("ul li:last").addClass(function(index) {
return "item-" + index;
});

给定一个有2个<li>元素的无序列表,这个例子将在最后一个<li>元素上加上"item-1"样式。

例子:

Example: 在匹配的元素上加上'selected'样式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<style>
p { margin: 8px; font-size:16px; }
.selected { color:blue; }
.highlight { background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p>
<p>and</p>
<p>Goodbye</p>
<script>
$("p").last().addClass("selected");
</script>
</body>
</html>

Demo:

Example: 在匹配的元素上加上'selected'和 'highlight' 样式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<style>
p { margin: 8px; font-size:16px; }
.selected { color:red; }
.highlight { background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p>
<p>and</p>
<p>Goodbye</p>
<script>
$("p:last").addClass("selected highlight");
</script>
</body>
</html>

Demo:

Example: Pass in a function to .addClass() to add the "green" class to a div that already has a "red" class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
<head>
<style>
div { background: white; }
.red { background: red; }
.red.green { background: green; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div>This div should be white</div>
<div class="red">This div will be green because it now has the "green" and "red" classes.
It would be red if the addClass function failed.</div>
<div>This div should be white</div>
<p>There are zero green divs</p>
<script>
$("div").addClass(function(index, currentClass) {
var addedClass;
if ( currentClass === "red" ) {
addedClass = "green";
$("p").text("There is one green div");
}
return addedClass;
});
</script>
</body>
</html>

Demo: