CSS变量出现前,从CSS传值给JS非常困难,甚至需要借助一些Hack的手法。现在使用CSS变量,你可以直接通过JS获取变量值并进行修改:
.breakpoints-data {
--phone: 480px;
--tablet: 800px;
}
const breakpointsData = document.querySelector('.breakpoints-data');
// GET
const phone = getComputedStyle(breakpointsData)
.getPropertyValue('--phone');
// SET
breakpointsData.style
.setProperty('--phone', 'custom');
使用CSS变量,定制和动态切换网站主题非常简单方便:
html {
--hue: 210; /* Blue */
--text-color-normal: hsl(var(--hue), 77%, 17%);
...
}
html[data-theme='dark'] {
--text-color-normal: hsl(var(--hue), 10%, 62%);
...
}
通过JS改变元素属性,动态切换主题:
document.documentElement.setAttribute('data-theme', 'dark')
document.documentElement.setAttribute('data-theme', 'light')