页面DOM里的每个节点上都有一个classList对象,程序员可以使用里面的方法新增、删除、修改节点上的CSS类。使用classList,程序员还可以用它来判断某个节点是否被赋予了某个CSS类。
添加类(add)
document.getElementById("myp").classList.add("mystyle");
为 <p> 元素添加多个类:
document.getElementById("myp").classList.add("mystyle", "anotherClass", "thirdClass");
移除类(remove)
使用remove方法,你可以删除单个CSS类:
document.getElementById("myp").classList.remove("mystyle");
移除多个类:
document.getElementById("myp").classList.remove("mystyle", "anotherClass", "thirdClass");
切换类(toggle)
这个方法的作用就是,当myp元素上没有这个CSS类时,它就新增这个CSS类;如果myp元素已经有了这个CSS类,它就是删除它。就是反转操作。
document.getElementById("myp").classList.toggle("newClassName");
myp.classList.toggle('myCssClass'); //现在是增加
myp.classList.toggle('myCssClass'); //现在是删除
是否存在类(contains)
检查是否含有某个CSS类:
var x = document.getElementById("myp").classList.contains("mystyle");
结果是true或者false。
length属性
返回类列表中类的数量。
查看 <p> 元素有多少个类名:
var x = document.getElementById("myp").classList.length; //3
获取获取 <p> 元素的所有类名:
<p id="myp" class="mystyle anotherClass thirdClass">I am a p element</p>
var x = document.getElementById("myp").classList;
item(index)
返回类名在元素中的索引值。索引值从 0 开始。如果索引值在区间范围外则返回 null
获取 <p> 元素的第一个类名(索引为0):
var x = document.getElementById("myp").classList.item(0); //mystyle
浏览器支持

但是IE9和IE9以前的版本不支持该属性,下面这个代码可以弥补这个遗憾:(来自网友代码)
if (!("classList" in document.documentElement)) {
Object.defineProperty(HTMLElement.prototype, 'classList', {
get: function() {
var self = this;
function update(fn) {
return function(value) {
var classes = self.className.split(/\s+/g),
index = classes.indexOf(value);
fn(classes, index, value);
self.className = classes.join(" ");
}
}
return {
add: update(function(classes, index, value) {
if (!~index) classes.push(value);
}),
remove: update(function(classes, index) {
if (~index) classes.splice(index, 1);
}),
toggle: update(function(classes, index, value) {
if (~index)
classes.splice(index, 1);
else
classes.push(value);
}),
contains: function(value) {
return !!~self.className.split(/\s+/g).indexOf(value);
},
item: function(i) {
return self.className.split(/\s+/g)[i] || null;
}
};
}
});
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END




















暂无评论内容