CSS变量的使用
:root {
--background-color: #fff
}
.dark {
--background-color: #23272e
}
定义好CSS变量后,将使用颜色的地方更改为var(--background-color)
,这样全局会使用root
中的变量,而加了class="dark"
的地方会使用dark
的变量,也就实现了颜色的定义
切换方法
// 添加
document.querySelector('body').classList.add("dark")
// 移除
document.querySelector('body').classList.remove("dark")
更改root中的变量
如果变量不再定义的dark
中,例如滚动条的轨道颜色,就需要直接更改root
中的变量,方法为
document.documentElement.style.setProperty('--scroll-bg-color-custom', '#2c313a')