如何使用JS编辑CSS变量?

我有这些CSS变量来控制我的项目的颜色,所以我可以做主题。

html { --main-background-image: url(../images/starsBackground.jpg); --main-text-color: #4CAF50; --main-background-color: rgba(0,0,0,.25); --beta-background-color: rgba(0,0,0,.85); } 

但无论我如何尝试更改属性(两个注释行分别尝试),我得到的最接近的不是有效属性。

 function loadTheme() { var htmlTag = document.getElementsByTagName("html"); var yourSelect = document.getElementById( "themeSelect" ); var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value ); // htmlTag[0].setAttribute('--main-text-color', '#FFCF40'); // $("html").css("--main-text-color","#FFCF40"); } 

错误消息

使用el.style.cssText属性或el.style.setPropertyel.setAttribute方法可以更改CSS变量。 在您的代码片段中,错误地使用了el.setAttribute ,这会导致您遇到的错误。 这是正确的方法:

 var html = document.getElementsByTagName('html')[0]; html.style.cssText = "--main-background-color: red"; 

要么

 var html = document.getElementsByTagName('html')[0]; html.style.setProperty("--main-background-color", "green"); 

要么

 var html = document.getElementsByTagName('html')[0]; html.setAttribute("style", "--main-background-color: green"); 

演示

以下演示使用CSS变量定义背景颜色,然后在加载后2秒使用JS片段更改它。

 window.onload = function() { setTimeout(function() { var html = document.getElementsByTagName('html')[0]; html.style.cssText = "--main-background-color: red"; }, 2000); }; 
 html { --main-background-image: url(../images/starsBackground.jpg); --main-text-color: #4CAF50; --main-background-color: rgba(0,0,0,.25); --beta-background-color: rgba(0,0,0,.85); } body { background-color: var(--main-background-color); } 

如果您正在使用:root

 :root { --somevar: black; } 

它将是documentElement。

 document.documentElement.style.setProperty('--somevar', 'green'); 

您可以简单地使用设置任意CSS属性的标准方法: setProperty

 document.body.style.setProperty('--background-color', 'blue'); 
 body { --background-color: red; background-color: var(--background-color); } 

原生解决方案

获取/设置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

您可以添加类似下面的内容(不使用类变量)

 function loadTheme() { var htmlTag = document.getElementById("myDiv"); var yourSelect = document.getElementById("themeSelect"); var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value); console.log("selected theme: " + selectedTheme); // reset class names htmlTag.className = ''; // add selected theme htmlTag.className = 'theme' + selectedTheme; } 
 .theme1 { color: blue; } .theme2 { color: red; } 
 
test

在CSS中定义包含各种主题样式( .theme1 {...} .theme2 {...}等)的类可能更容易,然后根据所选值使用JS更改类。