Accessing css variable in JS file

僤鯓⒐⒋嵵緔 提交于 2021-02-09 07:31:19

问题


I am having a CSS file which has some variable define

 @red: red-color
 @yello: yellow-color
 ....

I can use this variable in CSS file, But I want to know how can I access them in my JS file.


回答1:


Assuming you're using native CSS variables and not some preprocessor, take a look at this page. At the bottom there's a section called Values in JavaScript which describes how to access native CSS vars in JS code.

getComputedStyle(element).getPropertyValue("--my-var");

However if you are using a CSS preprocessor, it is not possible to retrieve the variables via JS since they're already processed in the build process.




回答2:


Those are not CSS variables, but LESS variables (as they start with "@")

Those get compiled into simple, static property declarations, so no way to change them at runtime (other than addressing every property).

IF you use proper CSS variables (aka CSS Custom Properties) you can easily access them with javascript at runtime and chage it with the style.setProperty method.

But they are not widely (enough) supported, so make sure to include a fallabck.



来源:https://stackoverflow.com/questions/48153360/accessing-css-variable-in-js-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!