我在我的项目中使用css根变量来随时动态更改所有元素的颜色。
我的CSS看起来像
:root{
--primaryColor:aliceblue;
--secondaryColor:blue;
--errorColor:#cc2511;
}
用于css
.contentCss {
background-color: var(--primaryColor);
}
我可以按如下方式访问javascript中的变量来动态更改值
document.documentElement.style.setProperty('--primaryColor', 'green');
它工作正常。我想获取数组中的所有变量,并根据这些动态更改每个变量的值。
此脚本将返回所有样式表中的根变量数组,从域提供。由于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
规则。
您可以使用键声明关联数组作为节点属性及其值,然后使用函数设置主题:
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);
>>编辑<<
Nadeem通过下面的评论更好地澄清了这个问题,不幸的是,我已经知道可以使用get :root
访问Window.getComputedStyle()
但是这不会返回CSS变量声明。
解决这个问题只是为了阅读css文件,解析变量并将它们填充到关联数组中,但即便如此,也可以假设您知道从哪里获取该css文件...
//an associative array that will hold our values
var cssVars = {};
var request = new XMLHttpRequest();
request.open('GET', './css/style.css', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
//Get all CSS Variables in the document
var matches = request.responseText.match(/(--)\w.+;/gi);
//Get all CSS Variables in the document
for(let match in matches) {
var property = matches[match];
//split the Variable name from its value
let splitprop = property.split(":")
//turn the value into a string
let value = splitprop[1].toString()
cssVars[splitprop[0]] = value.slice(0, -1); //remove ;
}
// console.log(cssVars);
// > Object {--primaryColor: "aliceblue", --secondaryColor: "blue", --errorColor: "#cc2511"}
// console.log(Object.keys(cssVars));
// > ["--primaryColor", "--secondaryColor", "--errorColor" ]
setTheme(cssVars)
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
console.log("There was a connection error");
};
request.send();
function setTheme(theme) {
var keys = Object.keys(theme)
for (key in keys) {
let prop = keys[key]
let color = theme[keys[key]];
console.log(prop, color);
// --primaryColor aliceblue etc...
}
}
如果你知道你的所有变量都将放在:root
中,并且它是你的第一个CSS文件中的第一个声明,你可以尝试这样的东西,你将得到一个Object内的所有变量:
var declaration = document.styleSheets[0].cssRules[0];
var allVar = declaration.style.cssText.split(";");
var result = {}
for (var i = 0; i < allVar.length; i++) {
var a = allVar[i].split(':');
if (a[0] !== "")
result[a[0].trim()] = a[1].trim();
}
console.log(result);
var keys = Object.keys(result);
console.log(keys);
//we change the first variable
document.documentElement.style.setProperty(keys[0], 'green');
//we change the variable --secondary-color
document.documentElement.style.setProperty(keys[keys.indexOf("--secondary-color")], 'red');
:root {
--primary-color: aliceblue;
--secondary-color: blue;
--error-color: #cc2511
}
p {
font-size: 25px;
color: var(--primary-color);
border:1px solid var(--secondary-color)
}
<p>Some text</p>
几年后......
您可以遍历所有样式(like in this answer),然后执行一些String fiddling以查找包含var(--
(或使用正则表达式)的所有规则。
也有点厚脸皮,但你不需要额外的装载
我今天需要类似的解决方案。这是一个quick one on codepen。
// 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));