问题
This question already has an answer here:
- Accessing a CSS custom property (aka CSS variable) through JavaScript 3 answers
Is there a way to access a css variable from javascript? Here my css variable declaration.
:root{
--color-font-general:#336699;
}
回答1:
Just the standard way:
- Get the computed styles with getComputedStyle
- Use getPropertyValue to get the value of the desired property
getComputedStyle(element).getPropertyValue('--color-font-general');
Example:
var style = getComputedStyle(document.body);
console.log(style.getPropertyValue('--color-font-general'));
:root { --color-font-general: #336699; }
回答2:
Use this:
window.getComputedStyle(document.documentElement).getPropertyValue('--color-font-general');
And you can change it like this:
document.documentElement.style.setProperty('--color-font-general', '#000');
source
来源:https://stackoverflow.com/questions/41725725/access-css-variable-from-javascript