.addClass( className )返回: jQuery
描述: 为每个匹配的元素添加指定的样式类名
-
添加的版本: 1.0.addClass( className )
-
className类型: String为每个匹配元素所要增加的一个或多个样式名。
-
-
添加的版本: 1.4.addClass( function(index, currentClass) )
-
function(index, currentClass)这个函数返回一个或更多用空格隔开的要增加的样式名。接收index 参数表示元素在匹配集合中的索引位置和html 参数表示元素上原来的 HTML 内容。在函数中
this
指向匹配元素集合中的当前元素。
-
值得注意的是这个方法不会替换一个样式类名。它只是简单的添加一个样式类名到元素上。
在jQuery 1.12/2.2 版本之前, .addClass()
方法操纵是选定元素的className
特性(property),不是class
属性(attribute)。一旦特性(property)改变,浏览器就会更新相应地的属性(attribute)。此行为的一个言外之意是,这种方法只适用于HTML
DOM语义的文档(例如,不是纯XML文档)。
在jQuery1.12/2.2中,改变了这种行为以改善对XML文档,包括SVG的支持。从这个版本开始,class
属性(attribute)被替换(注:这个版本开始,.addClass()
方法操作的是class
属性(attribute),而不是className
特性(property))。因此,..addClass()
可以在XML或SVG文档中使用。
对所有匹配的元素可以一次添加多个用空格隔开的样式类名, 像这样:
1
|
|
这个方法通常和.removeClass()
一起使用,用来切换元素的样式, 像这样:
1
|
|
这里, myClass
和 noClass
样式名在所有段落上被移除, 然后 yourClass
被添加。
自 jQuery 1.4开始, .addClass()
方法允许我们通过传递一个用来设置样式类名的函数。
1
2
3
|
|
给定一个有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
|
|
Demo:
Example: 在匹配的元素上加上'selected'和 'highlight' 样式。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
|
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
|
|