从javascript访问CSS变量

IT技术 javascript css css-variables
2021-01-26 15:15:26

有没有办法从javascript访问css变量?这是我的 css 变量声明。

:root {
  --color-font-general: #336699;
}
2个回答

只是标准方式:

  1. 获取计算样式 getComputedStyle
  2. 使用getPropertyValue以获得所需的属性的值
getComputedStyle(element).getPropertyValue('--color-font-general');

例子:

var style = getComputedStyle(document.body)
console.log( style.getPropertyValue('--bar') ) // #336699
console.log( style.getPropertyValue('--baz') ) // calc(2px*2)
:root { --foo:#336699; --bar:var(--foo); --baz:calc(2px*2); }

@EricMutta 我刚刚经历过这个。很烦人。为什么他们会在字符串中以一个前导空格返回?
2021-03-17 15:15:26
有没有办法在不引起回流的情况下做到这一点,因为 getComputedStyle 会这样做?
2021-03-30 15:15:26
请注意,返回的值具有前导空格,因此您将得到“#336699”而不是“#336699”。如果您尝试检查该值,这很重要(由于该前导空格,它可能不匹配,因此请考虑在检查之前对其进行修剪)。
2021-04-05 15:15:26
看起来它在 IE 10 中不起作用,任何指向正确方向的指针?
2021-04-06 15:15:26
@webkitfanz 您确实意识到 IE 不支持 css 变量,对吗?
2021-04-09 15:15:26

用这个:

window.getComputedStyle(document.documentElement).getPropertyValue('--color-font-general');

你可以像这样改变它:

document.documentElement.style.setProperty('--color-font-general', '#000');

来源

document.documentElement.style.setProperty('--color-font-general', '#000');如果你想改变它,实际上是这样。
2021-03-17 15:15:26
oop固定。谢谢!
2021-03-29 15:15:26
你也可以这样得到: element.style.getPropertyValue()
2021-04-03 15:15:26
@Rudieelement.style.getPropertyValue()只有在元素的内联样式上设置了变量时才有效(不是通过 CSS 规则)
2021-04-12 15:15:26