Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript获取数组中的所有css根变量并更改值_Javascript_Jquery_Css_Css Selectors_Css Variables - Fatal编程技术网

使用javascript获取数组中的所有css根变量并更改值

使用javascript获取数组中的所有css根变量并更改值,javascript,jquery,css,css-selectors,css-variables,Javascript,Jquery,Css,Css Selectors,Css Variables,我在我的项目中使用css根变量来随时动态更改所有元素的颜色 我的css看起来像 :root{ --primaryColor:aliceblue; --secondaryColor:blue; --errorColor:#cc2511; } 在css中使用 .contentCss { background-color: var(--primaryColor); } 我可以按如下方式访问javascript中的变量以动态更改值 document.documentElement.

我在我的项目中使用css根变量来随时动态更改所有元素的颜色

我的css看起来像

:root{
  --primaryColor:aliceblue;
  --secondaryColor:blue;
  --errorColor:#cc2511;
}
在css中使用

.contentCss {
  background-color: var(--primaryColor);
} 
我可以按如下方式访问javascript中的变量以动态更改值

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

它很好用。我想获取数组中的所有变量,并根据这些变量动态地更改每个变量的值

您可以将具有键的关联数组声明为节点属性及其值,然后使用函数设置主题:

var primaryColor = document.documentElement.style.getPropertyValue('--primaryColor');
var secondaryColor = document.documentElement.style.getPropertyValue('--secondaryColor');
var errorColor = document.documentElement.style.getPropertyValue('--errorColor');

var themeColors = {}
themeColors["--primaryColor"] = primaryColor;
themeColors["--secondaryColor"] = secondaryColor;
themeColors["--errorColor"] = errorColor;

function setTheme(theme) {
     for (key in theme) {
        let color = theme[key];
        document.documentElement.style.setProperty(key, color);
   }
 }
我使用Atom和Bootstrap的一个工作示例:

        var backgroundColor = document.documentElement.style.getPropertyValue('--blue');
        backgroundColor = "#dc3545";

        function setTheme(theme) {
          for (key in theme) {
            let color = theme[key];
            document.documentElement.style.setProperty(key, color);
          }
        }

        var theme = {}
        theme["--blue"] = backgroundColor;

        setTheme(theme);

>Edit=200&&request.status<400){ //获取文档中的所有CSS变量 var matches=request.responseText.match(/(-)\w.+;/gi); //获取文档中的所有CSS变量 for(让匹配进入匹配){ var属性=匹配项[match]; //将变量名与其值拆分 让splitprop=property.split(“:”) //将值转换为字符串 let value=splitprop[1].toString() cssVars[splitprop[0]]=value.slice(0,-1);//删除; } //console.log(cssVars); //>对象{--primaryColor:“aliceblue”,--secondaryColor:“blue”,--errorColor:#cc2511} //log(Object.keys(cssvar)); //>[“--primaryColor”、“--secondaryColor”、“--errorColor”] 设置主题(cssVars) }否则{ //我们到达了目标服务器,但它返回了一个错误 } }; request.onerror=函数(){ log(“存在连接错误”); }; request.send(); 函数setTheme(主题){ var keys=Object.keys(主题) 用于(输入键){ 让道具=钥匙[钥匙] 让颜色=主题[键[键]; 控制台日志(道具、颜色); //--primaryColor aliceblue等。。。 } }
如果您知道所有变量都将放在
:root
中,并且它是第一个CSS文件中的第一个声明,那么您可以尝试以下操作,您将获得对象中的所有变量:

var声明=document.styleSheets[0].cssRules[0];
var allVar=declaration.style.cssText.split(“;”);
var result={}
对于(变量i=0;i
:根目录{
--原色:aliceblue;
--次要颜色:蓝色;
--错误颜色:#cc2511
}
p{
字体大小:25px;
颜色:var(--原色);
边框:1px实心变量(--辅色)
}

一些文本

我今天需要一个类似的解决方案。这是一个例子

//可以传入一个特定样式表数组以进行优化
函数getAllCSSVariableNames(样式表=document.styleSheets){
var cssVars=[];
//循环每个样式表
for(var i=0;i
此脚本将返回所有样式表中的根变量数组,由域提供。由于CORS策略,无法访问域外样式表

Array.from(document.styleSheets)
  .filter(
    sheet =>
      sheet.href === null || sheet.href.startsWith(window.location.origin)
  )
  .reduce(
    (acc, sheet) =>
      (acc = [
        ...acc,
        ...Array.from(sheet.cssRules).reduce(
          (def, rule) =>
            (def =
              rule.selectorText === ":root"
                ? [
                    ...def,
                    ...Array.from(rule.style).filter(name =>
                      name.startsWith("--")
                    )
                  ]
                : def),
          []
        )
      ]),
    []
  );

注意:低阶样式表中的
root:
规则将覆盖父
root
规则

假设我在css中有200个变量,所以我必须写这一行var primaryColor=document.documentElement.style.getPropertyValue('--primaryColor');200次。我想要动态的。有趣的解决方案,非常干净,我考虑过使用
.cssRules[0]
,但我发现只读取了第一个
:root
元素。如果您有来自不同来源的多个索引,例如本地和CDN,则只读取第一个。@RLoniello是的,您可能会注意到我使用了
0
索引,如果您遵循这些索引,您将看到我获取了第一个CSS文件和此CSS文件中的第一条规则。。。所以你可以对另一个做同样的事情,你唯一需要知道的是顺序和索引。。。这是一个小缺点:)但是如果你知道你的CSS文件,这就不是问题;)@RLoniello将console.log与
document.styleSheets
一起使用,查看其中的内容,您将了解;)是的,我明白了:)请注意CDN样式表的加载顺序:P@RLoniello是的,如果你收到订单,很容易。。。但是
// could pass in an array of specific stylesheets for optimization
function getAllCSSVariableNames(styleSheets = document.styleSheets){
   var cssVars = [];
   // loop each stylesheet
   for(var i = 0; i < styleSheets.length; i++){
      // loop stylesheet's cssRules
      try{ // try/catch used because 'hasOwnProperty' doesn't work
         for( var j = 0; j < styleSheets[i].cssRules.length; j++){
            try{
               // loop stylesheet's cssRules' style (property names)
               for(var k = 0; k < styleSheets[i].cssRules[j].style.length; k++){
                  let name = styleSheets[i].cssRules[j].style[k];
                  // test name for css variable signiture and uniqueness
                  if(name.startsWith('--') && cssVars.indexOf(name) == -1){
                     cssVars.push(name);
                  }
               }
            } catch (error) {}
         }
      } catch (error) {}
   }
   return cssVars;
}

function getElementCSSVariables (allCSSVars, element = document.body, pseudo){
   var elStyles = window.getComputedStyle(element, pseudo);
   var cssVars = {};
   for(var i = 0; i < allCSSVars.length; i++){
      let key = allCSSVars[i];
      let value = elStyles.getPropertyValue(key)
      if(value){cssVars[key] = value;}
   }
   return cssVars;
}

var cssVars = getAllCSSVariableNames();
console.log(':root variables', getElementCSSVariables(cssVars, document.documentElement));
Array.from(document.styleSheets)
  .filter(
    sheet =>
      sheet.href === null || sheet.href.startsWith(window.location.origin)
  )
  .reduce(
    (acc, sheet) =>
      (acc = [
        ...acc,
        ...Array.from(sheet.cssRules).reduce(
          (def, rule) =>
            (def =
              rule.selectorText === ":root"
                ? [
                    ...def,
                    ...Array.from(rule.style).filter(name =>
                      name.startsWith("--")
                    )
                  ]
                : def),
          []
        )
      ]),
    []
  );