JS之classList对象

2019-12-21  本文已影响0人  鲁女女

html5为每一个元素新增了一个classList对象,classList对象保存着控制当前元素类名的各个方法和属性。
Element.classList 是一个只读属性,返回一个元素的类属性的实时 返回一个元素的类属性的实时DOMTokenList集合。

相比将 element.className 作为以空格分隔的字符串来使用,classList 是一种更方便的访问元素的类列表的方法。

length 返回类名的个数
add() 在原有的类名基础上添加一个类名
remove() 在原有的类名基础上 移出某一个类名
toggle() 如果有这个类名 则删除这个类名,如果没有 则添加减去
item() 根据索引 获取类名
contains() 判断元素是否包含某一个类名

方法

示例

<button id="btn">按钮</button>
<div class="box">
    <p id="con" class="con show">concon</p>
</div>
var oBtn = document.getElementById("btn");
var oCon = document.getElementById("con");
oBtn.onclick = function () {
    
    // oCon.className = "red";
    // console.log(oCon.className); //red

    oCon.className = "con show red";

    //这个red类已经存在于元素的属性中,那么它将被忽略
    oCon.className += " red";
    console.log(oCon.classList.length); //3

    //在原有的类名基础上添加一个类名
    //oCon.classList.add("red");

    // 在原有的类名基础上 移出某一个类名
    // oCon.classList.remove("con");

    // 如果有这个类名 则删除这个类名,如果没有 则添加减去
    //oCon.classList.toggle("blue");

    // 判断元素是否包含某一个类名
    //console.log(oCon.classList.contains("con"));

    // 根据索引 获取类名
    //console.log(oCon.classList.item(0)); //con
}
上一篇 下一篇

猜你喜欢

热点阅读