classList类名操作可以更加方便的对元素的类名进行增加,删除和切换
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.bg {
background-color: black;
}
</style>
</head>
<body>
<div class="one two"></div>
<button>开关灯</button>
<script>
//classList 返回元素的类名
var div = document.querySelector('div');
console.log(div.classList[1]);//返回div的第二个类名(索引号为1)
//添加类名 在后面追加类名并且不会覆盖之前的类名 前面不需要'.'
div.classList.add('three');
//删除类名
div.classList.remove('one');
//切换类
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
document.body.classList.toggle('bg');
})
</script>
</body>
</html>
使用document.body.classList.toggle('bg');的时候,当前元素有'bg'这个类名时删除这个类名,反之没有这个类名则添加这个类名到classList的后面