问题
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