1. API概要
-
length:表示元素类名的个数,只读
-
item():支持一个参数,为类名的索引,返回对应的类名,例如上例:
document.body.classList.item(0);
如果索引超出范围,例如:
document.body.classList.item(3);
结果是:null.
- add(): 支持一个类名字符串参数。表示往类名列表中新增一个类名;如果之前类名存在,则添加忽略。
例如:
document.body.classList.add("c");
document.body.classList.length // 3
- remove() 支持一个类名字符串参数。表示往类名列表中移除该类名。例如:
document.body.classList.remove("c");
document.body.classList.length // 2
-
toggle() 支持一个类名字符串参数。无则加勉,有则移除之意。若类名列表中有此类名,移除之,并返回false; 如果没有,则添加该类名,并返回true.
-
contains()
支持一个类名字符串参数。表示往类名列表中是否包含该类名。有点对应jQuery
中的hasClass
方法,注意,这里的是contains
而不是contain
,后面有个s哦!
返回值很易懂的。如果包含,则返回true, 不包含,则false. 例如:
document.body.classList.contains("c"); // false 因为"c"上面remove掉了
扩展一个adds方法,可以一次添加多个类名,多个类名以空格分隔:
DOMTokenList.prototype.adds = function(tokens) {
tokens.split(" ").forEach(function(token) {
this.add(token);
}.bind(this));
return this;
};
var clList = document.body.classList;
clList.adds("child1 child2 child3").toString(); // "a b c child1 child2 child3"
原文:https://www.zhangxinxu.com/wordpress/2013/07/domtokenlist-html5-dom-classlist-%E7%B1%BB%E5%90%8D/
网友评论