[英]Is there a way to make a constant “dark mode” by using local Storage?
我一直在制作一個帶有默認“亮模式”和暗模式按鈕的小型站點,以供夜間用戶將其更改為暗模式。 我想使用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'
是一個賦值,將'light'存儲在mode變量中。 但出於if語句的目的,它也是一個表達式,其結果為“ light”, 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.