从javascript访问CSS变量 [英] Access CSS variable from javascript

查看:93
本文介绍了从javascript访问CSS变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to access a css variable from javascript? Here my css variable declaration.

:root{
    --color-font-general:#336699;
}


推荐答案

只是标准方式:


  1. 使用 getComputedStyle

  2. 使用 getPropertyValue 获取所需属性的值

  1. Get the computed styles with getComputedStyle
  2. Use getPropertyValue to get the value of the desired property



getComputedStyle(element).getPropertyValue('--color-font-general');

示例:

var style = getComputedStyle(document.body);
console.log(style.getPropertyValue('--color-font-general'));

:root { --color-font-general: #336699; }

这篇关于从javascript访问CSS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆