classList属性的知识点整理

xiaoxiao2021-02-28  23

classLIst属性返回元素的类名,作为DOMTokenList对象

该属性用于在元素中添加、移出、切换css类

语法:elem.classList

方法:

add( String[,String]):添加指定的类值。如果这些类已经存在于元素的属性中,那么他们将被忽略

remove(String[,String]):删除指定的类值

item(Number):按集合中的索引返回类值

toggle(String[,force]):

当只有一个参数的时,切换class value ,即如果类存在,删除它,并返回false,如果类不存在,则添加它并返回true。当存在第二个参数时,如果第二个参数的计算结果为true,则添加指定的类值,如果计算结果为false,则删除它

contains(string):检查元素的类属性中是否存在指定的类值

属性

length:返回类列表中类的数量,该属性是只读的

嗯、一例胜千言,看个小例子:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .box{ width:100px; height:100px; border:1px solid #e15671; } .red{ background:red; } .width{ width:200px; } .height{ height:300px; } </style> </head> <body> <div class="box"> </div> </body> <script> var oBox = document.querySelector('.box'); var list = oBox.classList; console.log(list.length); document.onclick = function(){ list.add("red","width"); list.toggle("height"); console.log(list.length); list.toggle("width",list.length<4?true:false); oBox.innerHTML = list.item(2); console.log(list.contains("width")) } </script> </html>

代码复制过去,看看效果就很容易理解了,所以此处我就不再多说什么了,那这个是新添加的属性,兼容性肯定是要考虑的,请看下面:

下表中的数字,表示浏览器支持的第一个版本号

属性      Chrome            IE        Firefox         Safari          OperaclassList8.010.03.65.111.5
转载请注明原文地址: https://www.6miu.com/read-2100036.html

最新回复(0)