- 通过document.documentElement.style.setProperty()方法将变量设置为CSS变量。
- CSS3中引入了CSS变量的概念,使用var()函数代表变量名,从而使得CSS样式可以重复使用。通过使用var()函数,我们可以方便地引用一些在CSS预处理器中定义的变量,这些变量可以控制各种不同样式的输出。
JS 获取、设置 CSS 变量
:root{
--main-white:#ee0;
}
body{
background-color: var(--main-white);
}
.body_all{
--header-bg: var(--main-white);
position: relative;
width: 200px;
height: 30px;
background-color: var(--header-bg);
}
<body>
<div class="body_all"></div>
</body>
console.log(
getComputedStyle(document.querySelector('.body_all')).getPropertyValue('--header-bg'),
getComputedStyle(document.querySelector('.body_all')).getPropertyValue('--main-white'),
getComputedStyle(document.documentElement).getPropertyValue('--main-white')
)
document.querySelector('.body_all').style.setProperty('--header-bg', '#ccc')
document.documentElement.style.setProperty('--main-white', '#ccc');
注意事项
- document.querySelector(':root') === document.documentElement
- 优先级: js设置值>内联样式>:root选择器>html选择器
- document.documentElement.style.getPropertyValue只能获取内联样式的值,而且document.documentElement.style.setProperty('--rect', '7px');方式设置CSS变量会添加到内联样式中去
如果CSS变量不是内联样式定义,document.documentElement.style.getPropertyValue就获取不到
- getComputedStyle(document.documentElement).getPropertyValue获取到的始终是实际的值
- 四种方式赋值时,如果值包含多个空格,都是总会把多余空格变成一个空格。
js 添加、移除样式
mDom.classList.add("nav");
mDom.classList.remove('nav');
切换类(有则移除,无则添加)
let element = document.getElementById('myElement');
element.classList.toggle('toggle-class');
获取类数组
let element = document.getElementById('myElement');
let classes = element.classList;
检查是否包含特定类
let element = document.getElementById('myElement');
let hasClass = element.classList.contains('some-class');