实现原理
- 对于样式中跟随主题改变的属性值设置CSS变量,样式规则中使用这些变量;
- 定义切换主题的类名,在该类选择器中,改变CSS变量的值为对应主题;
- 点击切换主题时,将主题变量添加到html标签上
e.g.
<!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>
/* 第一步 :root 定义全局CSS变量 */
:root {
--theme-color: red;
--theme-bgc: pink;
--mycolor: yellow
}
/* 第二步 */
.theme_blue {
--theme-color: blue;
--theme-bgc: skyblue;
}
main {
width: 100px;
height: 100px;
background-color: var(--theme-bgc);
}
main p {
font-size: 20px;
color: var(--theme-color);
}
.variable {
/* 选择器内定义局部CSS变量 */
/* 读取规则:先从内部找,找不到去上一级,然后是全局 */
--mycolor: aqua;
--mysize: 15px;
/* calc() CSS中的计算函数 */
font-size: calc(var(--mysize)*2);
}
</style>
</head>
<body>
<main>
<p>主题切换</p>
</main>
<button>切换</button>
<div class="variable" style="color: var(--mycolor)">
CSS变量
</div>
<script>
const btn = document.getElementsByTagName('button')
const html = document.getElementsByTagName('html')
console.log(html)
btn[0].addEventListener('click', function () {
// 第三步
html[0].classList.toggle('theme_blue')
})
</script>
</body>
</html>