有没有办法使用本地存储进行常量"dark mode"?



我一直在制作一个带有默认"浅色模式"和暗模式按钮的小网站,以将其更改为夜间用户的深色模式。我想使用 JS中的localStorage使暗模式保持不变,因此当您按一次并转到站点上的另一个页面时,它会保持暗模式。但我似乎无法让它工作。

当我将 localStorage 键"模式"设置为"深色"时,当我转到该站点中的另一个页面时,它默认为浅色模式。

这是 js 代码:

let mode;
mode = localStorage.getItem('mode');
if (mode = 'light'){
    lightMode();
}else{
    darkMode();
}
function darkMode() {
    document.getElementById("title").style.color = "white";
    document.body.style.backgroundColor = "#040040";
    //code...
    document.getElementById("darkmodebtn").style.color = "black";
    document.getElementById("darkmodebtn").style.backgroundColor = "white";
    document.getElementById("darkmodebtn").onclick = lightMode;
    document.getElementById("darkmodebtn").innerHTML = "Light Mode";
    localStorage.setItem('mode', 'dark');
    mode = localStorage.getItem('mode');
}
function lightMode() {
    document.getElementById("title").style.color = "black";
    document.body.style.backgroundColor = "lightblue";
    //more code...
    document.getElementById("darkmodebtn").style.color = "white";
    document.getElementById("darkmodebtn").style.backgroundColor = "black";
    document.getElementById("darkmodebtn").onclick = darkMode;
    document.getElementById("darkmodebtn").innerHTML = "Dark Mode";
    localStorage.setItem('mode', 'light');
    mode = localStorage.getItem('mode');
}

这是按钮的 html:

<div id="darkmode">
    <button id="darkmodebtn" onclick="darkMode()">Dark Mode</button>
</div>

当我打开网站上的任何页面时,有一个错误,即:

Uncaught TypeError: Cannot read property 'style' of null
    at lightMode (script.js:79)
    at script.js:57

它描述了lightMode函数中第一行的错误,但我不知道这是否是问题的一部分。

问题出在以下行上:

if (mode = 'light')

mode = 'light'是一个赋值,将"光"存储在模式变量中。但出于 if 语句的目的,它也是一个计算结果为"光"的表达式,if将其解释为 true 。因此,您将始终处于灯光模式。

if (mode === 'light')是你想要的。

要检查条件是true还是false,您必须使用===来比较它们。

if (mode === 'light'){
    lightMode();
}else{
    darkMode();
}

要修复错误Uncaught TypeError: Cannot read property 'style' of null

您应该在所有 DOM 生成后放置代码,

例如:

<html>
    <head></head>
    <body>
        <div id="title"></div>
        <script>
            // place your code here!
        </script>
    </body>
</html>

您可以将两个单独的 css 文件用于不同的模式。

if(lightmode===true) {
  document.getElementById("stylesheet").setAttrubute("href","light.css");}
else {
  ...//else block
}

最新更新