classList 属性返回元素的类名,作为 DOMTokenList 对象。
该属性用于在元素中添加,移除及切换 CSS 类。
classList 属性是只读的,但你可以使用 add() 和 remove() 方法修改它。
常用方法
add(class1, class2, …):在元素中添加一个或多个类名。
document.getElementById("myDIV").classList.add("a");
remove(class1, class2, …):移除元素中一个或多个类名。
document.getElementById("myDIV").classList.remove("a");
toggle(class):在元素中切换类名。也就是如果有这个类名就删除这个类名,如果没有这个类名就添加这个类名
这个元素可以让我们更容易写开关灯特效,比如:
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.choose {
background-color: #000;
}
</style>
</head>
<body>
<button id="btn">开关灯</button>
<script>
var btn = document.getElementById('btn')
btn.onclick = function () {
document.body.classList.toggle("choose")
}
</script>
</body>
</html>