有时候,我们会有需求就是在不同的条件下让页面的某个组件或者背景按照一定的规则进行变化,实现的思路是,给标签在特定条件赋不同或者赋多个选择器去改变他的样式,那么随着需求的变化多端,我们想要让js来操作实现给dom添加选择器,有三种方式,
第一种,直接调用dom自带的属性style进行选择对应的样式属性赋值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: #000;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
const box = document.querySelector(".box")
// 这种方式也可以用
box.style["background-color"] = 'pink'
// box.style.backgroundColor = 'pink'
</script>
</body>
</html>
第二种,className属性,直接给dom添加一个新的样式选择器,但是有个弊端,会新选择器覆盖掉就选择器。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
background-color: pink;
}
.box {
width: 300px;
height: 500px;
background-color: blue;
}
</style>
</head>
<body>
<div></div>
<script>
const div = document.querySelector("div")
// className有个弊端就是 会新值覆盖了旧值 解决办法就是每次赋值的时候 把两个类名都赋值上去
div.className = "box"
</script>
</body>
</html>
第三种,classList属性,可以添加也可以删除样式也可以替换选择器。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: #fff;
color: aqua;
}
.active {
background-color: red;
font-size: 800;
color: blue;
}
</style>
</head>
<body>
<div class="box">文字</div>
<script>
const box = document.querySelector(".box")
// 删除类名 remove() 切换类 toggle()
box.classList.add("active")
</script>
</body>
</html>