List CSS custom properties (CSS Variables)

后端 未结 2 1752
醉酒成梦
醉酒成梦 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:36

    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
    }

提交回复
热议问题