Access CSS variable from javascript [duplicate]

那年仲夏 提交于 2019-11-26 13:47:38

问题


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:

  1. Get the computed styles with getComputedStyle
  2. 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

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