ITeye博客

HTML 5--classList

小丑鱼0703 · 2014-04-25 14:19 · html5 · Web前端 · Markdown

HTML5新增了一种操作类名的方式,可以让操作更简单也更安全,那就是为所有元素添加classList属性。这个classList属性是新集合类型DOMTokenList【DOM标记列表】的实例。与其它DOM集合类似,DOMTokenList是一个表示自己包含多少元素的length属性,而要取得每个元素可以使用item()方法,也可以使用方扩号语法。

这个类型还定义如下方法: add(value):将指定的字符串值添加到列表中。如果值已经存在,就不添加了。 contains(value):表示列表中是否存在给定的值,如果存在则返回true,否则返回false。 remove(value):从列表中删除指定的字符串。 toggle(value):如果列表中已经存在给定的值,删除它;如果列表中没有给定的值,添加它。

<body class="a b c"></body>

document.body.classList;//结果:["a", "b", "c"]
document.body.classList.add("c");//不添加返回undefined
document.body.classList.add("d");//添加成功返回undefined
document.body.classList.contains("d");//返回true
document.body.classList.contains("e");//返回false
document.body.classList.remove("d");//删除成功返回undefined
document.body.classList.toogle("f");//不存在的情况,添加"f"
document.body.classList.toogle("f");//存在的情况,删除"f"

item() 支持一个参数,为类名的索引,返回对应的类名:

document.body.classList.item(0);//结果:“a”

length 属性,表示元素类名的个数:

document.body.classList.length();//结果:“3”

浏览器兼容性: Chrome 8+ FF 3.6+ Opera 11.50+ Safari 5.1+

某人整理的这篇还不错,移步http://zhangyaochun.iteye.com/blog/1473167 http://www.zhangxinxu.com/wordpress/2013/07/domtokenlist-html5-dom-classlist-%E7%B1%BB%E5%90%8D/

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。