如下代码,我们点击#div 这个元素改变css样式变量 ,然后其他的p元素的样式也会改变。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
:root {
--color: red;
}
#div {
margin: 100px auto;
width: 200px;
height: 200px;
background-color: var(--color);
cursor: pointer;
}
p {
text-align: center;
color: var(--color);
}
</style>
</head>
<body>
<div id="div"></div>
<p>hello</p>
<p>blog</p>
</body>
<script>
const div = document.querySelector("#div");
const htmlStyle = document.documentElement.style;
div.onclick = function() {
if (htmlStyle.getPropertyValue("--color").trim() === "blue") {
htmlStyle.setProperty("--color", "red");
} else {
htmlStyle.setProperty("--color", "blue");
}
console.log(htmlStyle.getPropertyValue("--color").trim());
};
</script>
</html>
参考链接
http://www.ruanyifeng.com/blog/2017/05/css-variables.html