1.className 的作用: 获取或设置指定元素的 class 属性的值。
2.className 的特点:当使用className为标签赋值新类名时,旧类名会被覆盖
代码如下:
<!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>
.yellow {
width: 300px;
height: 300px;
background-color: skyblue;
}
.pink {
width: 100px;
height: 100px;
background: pink;
color: hotpink;
}
.green {
color: green;
}
</style>
</head>
<body>
<div class="box yellow">随便一些文本内容</div>
<script>
// 获取 DOM 节点
const box = document.querySelector('.box')
const div = document.querySelector('div')
//输出box结点(标签)所拥有的类名
document.write(box.className + '<br>')
// 使用className将新类名赋值给标签,旧类名会被覆盖
//即给box添加样式pink
box.className = 'pink'
//输出box结点(标签)所拥有的类名
document.write(box.className)
box.className = 'green' //即给box添加样式green
</script>
</body>
</html>
因此为了解决className 容易覆盖以前的类名的问题,我们可以通过classList方式追加和删除类名
3、Element.classList
是一个只读属性,返回一个元素 class
属性的动态 DOMTokenList 集合。这可以用于操作 class 集合。
代码如下:
<!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>
div {
width: 200px;
height: 200px;
background-color: pink;
}
.active {
width: 300px;
height: 300px;
background-color: greenyellow;
margin-left: 100px;
}
</style>
</head>
<body>
<div class="gg one"></div>
<script>
// 1.获取元素
let box = document.querySelector('div')
// 2.使用 classList API 移除、添加类值
// 原来:
document.write('原来:' + box.className + '<br>')
// remove() 移除 类
box.classList.remove('one')
document.write(box.className + '<br>')
// add是个方法 添加 追加
box.classList.add('active')
document.write(box.className + '<br>')
// 切换类(如果 one类值已存在,则移除它,否则添加它)
let re = box.classList.toggle('one')
document.write(box.className + '<br>')
let re2 = box.classList.toggle('active')
document.write(box.className + '<br>')
</script>
</body>
</html>