[英]HTML Local Storage Dark Mode Using JavaScript
我試圖為我的網站制作一個完整的暗模式。 快完成了,但我有一個問題。 當我重新加載頁面時,暗模式返回默認的亮模式。 我怎樣才能解決這個問題? 我嘗試了一些代碼,但沒有用。 我想使用本地存儲,但我不知道如何將其添加到我的代碼中。 有人可以幫我弄這個嗎? 這是我的示例代碼:
function darkmode() { var element = document.body; element.classList.toggle("dark-mode"); }
<html> <head> <style> .card { background-color: red; color: green; } .dark-mode .card { background-color: black; color: white; } </style> </head> <body> <button onclick="darkmode()">DARK MODE</button> <div class="card"> <h2>Title</h2> <div class="fkimg" style="height: 100px; width: 20%;">IMAGE</div> <a>Some text</a> </div> </body> </html>
對於您的示例代碼,似乎最好的方法是向darkmode
函數添加一些darkmode
:
function darkmode() {
// all values retrieved from localStorage will be strings
const wasDarkmode = localStorage.getItem('darkmode') === 'true';
localStorage.setItem('darkmode', !wasDarkmode);
const element = document.body;
element.classList.toggle('dark-mode', !wasDarkmode);
}
function onload() {
document.body.classList.toggle('dark-mode', localStorage.getItem('darkmode') === 'true');
}
<html>
<head>...</head>
<body onload="onload()">
...
</body>
</html>
MDN localStorage 參考: https : //developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.