问题描述
我有一个 CSS
文件,其中包含一些变量define
I am having a CSS
file which has some variable define
@red: red-color
@yello: yellow-color
....
我可以在 CSS
文件中使用此变量,但是我想知道如何在 JS
文件中访问它们.
I can use this variable in CSS
file, But I want to know how can I access them in my JS
file.
推荐答案
假设您使用的是本机CSS变量而不是某些预处理程序,请查看此页面.底部有一个名为 JavaScript中的值的部分,其中描述了如何访问JS代码中的本机CSS变量.
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");
但是,如果您使用CSS预处理器,则无法通过JS检索变量,因为它们已在构建过程中处理过.
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.
这篇关于在JS文件中访问CSS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!