Mor*_*anR 6 html javascript css css3 css-variables
我在样式表中设置了一些CSS自定义属性:
:root {
--bc: #fff;
--bc-primary: #eee;
--bc-secondary: #ddd;
}
Run Code Online (Sandbox Code Playgroud)
如果我已经知道CSS变量的名称,我可以单独检索它们:
console.log(getComputedStyle(document.body).getPropertyValue('--bc'));
// #fff
Run Code Online (Sandbox Code Playgroud)
但是,如果我想将CSS变量及其值的列表拉出来,那该怎么办呢?
LGS*_*Son 11
一种可能的解决方案是解析document.styleSheets,然后将规则拆分为属性/值
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]);
}
}
}
}, '');
}
}, '');Run Code Online (Sandbox Code Playgroud)
:root {
--bc: #fff;
--bc-primary: #eee;
--bc-secondary: #ddd;
}Run Code Online (Sandbox Code Playgroud)
基于LGSon的回答,这里有一些类似的东西,但使用map, filter, 并flat使其更容易逐行阅读。
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);Run Code Online (Sandbox Code Playgroud)
:root {
--foo: #fff;
--bar: #aaa
}Run Code Online (Sandbox Code Playgroud)