【发布时间】:2016-10-14 14:06:46
【问题描述】:
好的,我正在为我的网页创建一个允许用户更改主题的系统。我想通过将所有颜色作为变量来实现这一点,并且颜色在 CSS 的 :root 部分中设置。
我想做的是通过 JavaScript 更改这些颜色。我查找了如何做到这一点,但我尝试过的任何事情都没有真正正常工作。这是我当前的代码:
CSS:
:root {
--main-color: #317EEB;
--hover-color: #2764BA;
--body-color: #E0E0E0;
--box-color: white;
}
JS:
(设置主题的代码,单击按钮即可运行)- 我没有费心将 :root 更改添加到其他 2 个主题,因为它不适用于深色主题
function setTheme(theme) {
if (theme == 'Dark') {
localStorage.setItem('panelTheme', theme);
$('#current-theme').text(theme);
$(':root').css('--main-color', '#000000');
}
if (theme == 'Blue') {
localStorage.setItem('panelTheme', 'Blue');
$('#current-theme').text('Blue');
alert("Blue");
}
if (theme == 'Green') {
localStorage.setItem('panelTheme', 'Green');
$('#current-theme').text('Green');
alert("Green");
}
}
(加载 html 时运行的代码)
function loadTheme() {
//Add this to body onload, gets the current theme. If panelTheme is empty, defaults to blue.
if (localStorage.getItem('panelTheme') == '') {
setTheme('Blue');
} else {
setTheme(localStorage.getItem('panelTheme'));
$('#current-theme').text(localStorage.getItem('panelTheme'));
}
}
它显示警报,但实际上并没有改变任何东西。有人能指出我正确的方向吗?
【问题讨论】:
-
文档准备好后你的js是否在运行?你如何确定它“没有改变任何东西”?将您的示例更改为更接近minimal reproducible example
-
用更多代码更新了 OP,抱歉。
-
您期望更改的内容仍然不明显。例如,在您的控制台上,您可以输入
$(':root').css("background-color", "#000000")并查看事情的变化。因此,如果没有发生视觉变化,问题可能不是您的代码(除非它在文档准备好之前运行) -
我想用JS改变变量的颜色。例如,在我的示例中,我试图将 --main-color 从 #317EEB 更改为 #000000。
-
打开控制台。运行设置颜色的语句。运行查询颜色的语句。看看你是否得到你设置的东西。
标签: javascript html css