概述 .removeClass( [className ] )
返回值:jQuery
描述:移除集合中每个匹配元素上一个,多个或全部样式。
String
如果一个样式类名作为一个参数,只有这样式类会被从匹配的元素集合中删除 。 如果没有样式名作为参数,那么所有的样式类将被移除。
在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文档中使用。
从所有匹配的每个元素中同时移除多个用空格隔开的样式类 ,像这样:
$('p').removeClass('myClass yourClass')
这个方法通常和 .addClass() 一起使用用来切换元素的样式, 像这样:
$('p').removeClass('myClass noClass').addClass('yourClass');
这里从所有段落删除 myClass 和 noClass 样式类, 然后 yourClass 样式被添加。
用其他样式类替换现有的样式类,我们可以使是有 .attr('class', 'newClass') 替换.
从 jQuery 1.4开始, .removeClass() 方法允许我们指定一个函数作为参数,返回将要被删除的样式。
$('li:last').removeClass(function() {
return $(this).prev().attr('class');
});
上例中,移除了最后一个 <li> 的样式,该样式是倒数第二个 <li> 的样式。
示例
从匹配的元素中删除 'selected' 类
$("p").removeClass("selected");
删除匹配元素的所有类
$("p").removeClass();
删除最后一个元素上与前面重复的class
$('li:last').removeClass(function() {
return $(this).prev().attr('class');
});
从匹配的元素中移除“blue”样式类。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>removeClass demo</title>
<style>
p {
margin: 4px;
font-size: 16px;
font-weight: bolder;
}
.blue {
color: blue;
}
.under {
text-decoration: underline;
}
.highlight {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.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>
运行一下
从匹配的元素中移除“blue”和“under”样式类。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>removeClass demo</title>
<style>
p {
margin: 4px;
font-size: 16px;
font-weight: bolder;
}
.blue {
color: blue;
}
.under {
text-decoration: underline;
}
.highlight {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.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>
运行一下
从匹配的元素中移除所有样式类。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>removeClass demo</title>
<style>
p {
margin: 4px;
font-size: 16px;
font-weight: bolder;
}
.blue {
color: blue;
}
.under {
text-decoration: underline;
}
.highlight {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.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>
运行一下