js获取设置的css变量的值

726 阅读1分钟
  • 通过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>
//通过js获取已经设置好的css变量值,getPropertyValue()获取CSS变量
//document.documentElement.style.getPropertyValue('--testColor')

//getComputedStyle(document.documentElement).getPropertyValue('--main-white') //获取根元素css变量
console.log(
  getComputedStyle(document.querySelector('.body_all')).getPropertyValue('--header-bg'),
  getComputedStyle(document.querySelector('.body_all')).getPropertyValue('--main-white'),
  getComputedStyle(document.documentElement).getPropertyValue('--main-white')
)

//通过js设置css变量
//设置.body_all元素css变量
document.querySelector('.body_all').style.setProperty('--header-bg', '#ccc')
//设置根元素css变量
document.documentElement.style.setProperty('--main-white', '#ccc');

注意事项

  1. document.querySelector(':root') === document.documentElement
  2. 优先级: js设置值>内联样式>:root选择器>html选择器
  3. document.documentElement.style.getPropertyValue只能获取内联样式的值,而且document.documentElement.style.setProperty('--rect', '7px');方式设置CSS变量会添加到内联样式中去 如果CSS变量不是内联样式定义,document.documentElement.style.getPropertyValue就获取不到
  4. getComputedStyle(document.documentElement).getPropertyValue获取到的始终是实际的值
  5. 四种方式赋值时,如果值包含多个空格,都是总会把多余空格变成一个空格。

js 添加、移除样式

// mDom 是要添加样式的元素。nav 是要添加的样式名。
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');