List CSS custom properties (CSS Variables)

后端 未结 2 1756
醉酒成梦
醉酒成梦 2021-01-02 19:20

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

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

I can re

2条回答
  •  温柔的废话
    2021-01-02 19:53

    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: #ffffd;
    }

提交回复
热议问题