List CSS custom properties (CSS Variables)

三世轮回 提交于 2019-12-30 04:51:45

问题


I've set some CSS custom properties in my stylesheet:

:root {
    --bc: #fff;
    --bc-primary: #eee;
    --bc-secondary: #ddd;
}

I can retrieve them individually if I already know the name of the CSS variable like so:

console.log(getComputedStyle(document.body).getPropertyValue('--bc'));

// #fff

But if I wanted to pull a list of CSS variables and their values out, how would that be done?


回答1:


One possible solution would be to parse the document.styleSheets, and then split the rules into properties/values

var allCSS = [].slice.call(document.styleSheets)
  .reduce(function(prev, styleSheet) {
    if (styleSheet.cssRules) {
      return prev + [].slice.call(styleSheet.cssRules)
        .reduce(function(prev, cssRule) {        
          if (cssRule.selectorText == ':root') {
            var css = cssRule.cssText.split('{');
            css = css[1].replace('}','').split(';');
            for (var i = 0; i < css.length; i++) {
              var prop = css[i].split(':');
              if (prop.length == 2 && prop[0].indexOf('--') == 1) {
                console.log('Property name: ', prop[0]);
                console.log('Property value:', prop[1]);
              }              
            }
          }
        }, '');
    }
  }, '');
:root {
    --bc: #fff;
    --bc-primary: #eee;
    --bc-secondary: #ddd;
}



回答2:


Based on LGSon's answer here is something similar but using map, filter, and flat to make it easier to read line by line.

const variables = [].slice.call(document.styleSheets)
    .map(styleSheet => [].slice.call(styleSheet.cssRules))
    .flat()
    .filter(cssRule => cssRule.selectorText === ':root')
    .map(cssRule => cssRule.cssText.split('{')[1].split('}')[0].trim().split(';'))
    .flat()
    .filter(text => text !== "")
    .map(text => text.split(':'))
    .map(parts => ({key: parts[0].trim(), value: parts[1].trim() }))
;

console.log(variables);
:root {
    --foo: #fff;
    --bar: #aaa
}


来源:https://stackoverflow.com/questions/45763121/list-css-custom-properties-css-variables

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