我有这些 CSS 变量来控制我的元素的颜色,所以我可以做主题。
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
然而,无论我如何尝试更改属性(分别尝试的两条注释行),我得到的最接近的结果是返回无效属性。
function loadTheme() {
var htmlTag = document.getElementsByTagName("html");
var yourSelect = document.getElementById( "themeSelect" );
var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
// htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
// $("html").css("--main-text-color","#FFCF40");
}
最佳答案
原来可以使用 el.style.cssText
属性或 el.style.setProperty
或 el.setAttribute
更改 CSS 变量方法。在您的代码片段中 el.setAttribute
被错误地使用,这导致了您遇到的错误。正确的方法是:
document.documentElement.style.cssText = "--main-background-color: red";
或
document.documentElement.style.setProperty("--main-background-color", "green");
或
document.documentElement.setAttribute("style", "--main-background-color: green");
演示
以下演示使用 CSS 变量定义背景颜色,然后在加载 2 秒后使用 JS 代码片段更改它。
window.onload = function() {
setTimeout(function() {
document.documentElement.style.cssText = "--main-background-color: red";
}, 2000);
};
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
body {
background-color: var(--main-background-color);
}
这显然只适用于支持 CSS 变量的浏览器。
关于javascript - 如何使用 JS 编辑 CSS 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59211507/