好吧,我正在为我的网页创建一个系统,允许用户更改主题.我想要实现这一点的方法是将所有颜色作为变量,并在CSS的根部分中设置颜色.
我想要做的是通过JavaScript更改这些颜色.我抬头看看怎么做,但我尝试过的任何事情都没有.这是我目前的代码:
CSS:
:root {
--main-color: #317EEB;
--hover-color: #2764BA;
--body-color: #E0E0E0;
--box-color: white;
}
Run Code Online (Sandbox Code Playgroud)
JS:
(设置主题的代码,单击按钮运行) - 我没有费心将:root更改添加到其他2个主题,因为它不适用于Dark主题
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");
}
}
Run Code Online (Sandbox Code Playgroud)
(加载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');
} …Run Code Online (Sandbox Code Playgroud)