<!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>
.item{
width: 100px;
height: 100px;
background-color: red;
color: black;
border-radius: 10px;
}
</style>
</head>
<body>
<button id="btn">666</button>
<div id="box" class="item" item1 item2></div>
<script>
// .className
console.log(box.className)
// 直接赋值
box.className = "item item2"
// classList 打印出来个数组
console.log(box.classList)
// 增加
box.classList.add("item333333")
// 删除
box.classList.remove("item")
// 切换toggle
box.classList.toggle
btn.onclick = function(){
box.classList.toggle("item")
}
</script>
</body>
</html>
JavaScript ---操作元素类名
最新推荐文章于 2025-01-10 10:39:51 发布