.removeClass()


.removeClass( [className ] )返回: jQuery

描述: 移除集合中每个匹配元素上一个,多个或全部样式。

  • 添加的版本: 1.0.removeClass( [className ] )

    • className
      类型: String
      每个匹配元素移除的一个或多个用空格隔开的样式名。
  • 添加的版本: 1.4.removeClass( function(index, class) )

    • function(index, class)
      类型: Function()
      一个函数,返回一个或多个将要被移除的样式名。index 参数表示在所有匹配元素的集合中当前元素的索引位置。class 参数表示原有的样式名。

如果一个样式类名作为一个参数,只有这样式类会被从匹配的元素集合中删除 。 如果没有样式名作为参数,那么所有的样式类将被移除。

在jQuery 1.12/2.2 版本之前, .removeClass()方法操纵是选定元素的className特性(property),不是class属性(attribute)。一旦特性(property)改变,浏览器就会更新相应地的属性(attribute)。此行为的一个言外之意是,这种方法只适用于HTML DOM语义的文档(例如,不是纯XML文档)。

在jQuery1.12/2.2中,改变了这种行为以改善对XML文档,包括SVG的支持。从这个版本开始,class 属性(attribute)被替换(注:这个版本开始,.addClass()方法操作的是class 属性(attribute),而不是className特性(property))。因此,..removeClass()可以在XML或SVG文档中使用。

从所有匹配的每个元素中同时移除多个用空格隔开的样式类 ,像这样:

1
$('p').removeClass('myClass yourClass')

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

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

这里从所有段落删除 myClassnoClass 样式类, 然后 yourClass 样式被添加。

用其他样式类替换现有的样式类,我们可以使是有 .attr('class', 'newClass') 替换.

从 jQuery 1.4开始, .removeClass() 方法允许我们指定一个函数作为参数,返回将要被删除的样式。

1
2
3
$('li:last').removeClass(function() {
return $(this).prev().attr('class');
});

上例中,移除了最后一个 <li> 的样式,该样式是倒数第二个 <li> 的样式。

例子:

Example: 从匹配的元素中移除“blue”样式类。

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: 4px; font-size:16px; font-weight:bolder; }
.blue { color:blue; }
.under { text-decoration:underline; }
.highlight { background:yellow; }
</style>
<script src="//code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p class="blue under">Hello</p>
<p class="blue under highlight">and</p>
<p class="blue under">then</p>
<p class="blue under">Goodbye</p>
<script>$("p:even").removeClass("blue");</script>
</body>
</html>

Demo:

Example: 从匹配的元素中移除“blue”和“under”样式类。

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

Demo:

Example: 从匹配的元素中移除所有样式类。

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: 4px; font-size:16px; font-weight:bolder; }
.blue { color:blue; }
.under { text-decoration:underline; }
.highlight { background:yellow; }
</style>
<script src="//code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p class="blue under">Hello</p>
<p class="blue under highlight">and</p>
<p class="blue under">then</p>
<p class="blue under">Goodbye</p>
<script>$("p:eq(1)").removeClass();</script>
</body>
</html>

Demo: