通过JavaScript访问CSS自定义属性(也称为CSS变量)

你如何使用JavaScript(plain或jQuery)获取和设置CSS自定义属性(使用样式表中的var(…)访问的属性)?

这是我不成功的尝试:单击按钮更改通常的font-weight属性,但不更改自定义--mycolor属性:

     body { --mycolor: yellow; background-color: var(--mycolor); }    

Let's try to make this text bold and the background red.

function plain_js() { document.body.style['font-weight'] = 'bold'; document.body.style['--mycolor'] = 'red'; }; function jQuery_() { $('body').css('font-weight', 'bold'); $('body').css('--mycolor', 'red'); }

你可以使用document.body.style.setProperty('--name', value);

 var bodyStyles = window.getComputedStyle(document.body); var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get document.body.style.setProperty('--foo-bar', newValue);//set 

更多信息在这里 。

原生解决方案

获取/设置CSS3变量的标准方法.setProperty().getPropertyValue()

如果您的变量是Globals(在:root声明),则可以使用以下内容来获取和设置它们的值。

 // setter document.documentElement.style.setProperty('--myVariable', 'blue'); // getter document.documentElement.style.getPropertyValue('--myVariable'); 

但是,getter将仅使用.setProperty()返回var的值(如果已设置.setProperty() 。 如果已经通过CSS声明设置,将返回undefined 。 在这个例子中检查它:

 let c = document.documentElement.style.getPropertyValue('--myVariable'); alert('The value of --myVariable is : ' + (c?c:'undefined')); 
 :root{ --myVariable : red; } div{ background-color: var(--myVariable); } 
  
Red background set by --myVariable

以下示例说明了如何使用JavaScript或jQuery更改背景,利用自定义CSS属性(也称为CSS变量)(请参阅此处 )。 额外:代码还指示了如何使用CSS变量来更改字体颜色。

 function plain_js() { // need DOM to set --mycolor to a different color d.body.style.setProperty('--mycolor', 'red'); // get the CSS variable ... bodyStyles = window.getComputedStyle(document.body); fontcolor = bodyStyles.getPropertyValue('--font-color'); //get // ... reset body element to custom property's new value d.body.style.color = fontcolor; dg("para").style["font-weight"] = "bold"; this.style.display="none"; }; function jQuery_() { $("body").get(0).style.setProperty('--mycolor','#f3f'); $("body").css("color",fontcolor); $("#para").css("fontWeight","bold"); $(this).css("display","none"); } var bodyStyles = null; var fontcolor = ""; var d = document; dg = d.getElementById; dg("red").addEventListener("click",plain_js); dg("pink").addEventListener("click",jQuery_); 
 :root { --font-color:white; --mycolor:yellow; } body { background-color: var(--mycolor); color:#090; } #para { font: 90% Arial,Helvetica; font-weight:normal; } #red { background:red; } #pink { background:#f3f; } 
  

Let's try to make the background red or pink and change the text to white and bold.