如下代码,我们点击#div 这个元素改变 css 样式变量 ,然后其他的 p 元素的样式也会改变。
1 |
|
2 | <html lang="en"> |
3 | <head> |
4 | <meta charset="UTF-8" /> |
5 | <meta name="viewport" content="width=device-width, initial-scale=1.0" /> |
6 | <meta http-equiv="X-UA-Compatible" content="ie=edge" /> |
7 | <title>Document</title> |
8 | <style> |
9 | :root { |
10 | --color: red; |
11 | } |
12 | |
13 | #div { |
14 | margin: 100px auto; |
15 | width: 200px; |
16 | height: 200px; |
17 | background-color: var(--color); |
18 | cursor: pointer; |
19 | } |
20 | p { |
21 | text-align: center; |
22 | color: var(--color); |
23 | } |
24 | </style> |
25 | </head> |
26 | <body> |
27 | <div id="div"></div> |
28 | <p>hello</p> |
29 | <p>blog</p> |
30 | </body> |
31 | <script> |
32 | const div = document.querySelector("#div"); |
33 | const htmlStyle = document.documentElement.style; |
34 | div.onclick = function() { |
35 | if (htmlStyle.getPropertyValue("--color").trim() === "blue") { |
36 | htmlStyle.setProperty("--color", "red"); |
37 | } else { |
38 | htmlStyle.setProperty("--color", "blue"); |
39 | } |
40 | console.log(htmlStyle.getPropertyValue("--color").trim()); |
41 | }; |
42 | </script> |
43 | </html> |
参考链接
http://www.ruanyifeng.com/blog/2017/05/css-variables.html