我正在尝试实现一个深色主题,一旦用户刷新页面或关闭浏览器,它将保留该设置,直到用户决定更改它为止。如何使用本地存储实现呢?我没用过您的帮助将不胜感激!
function change() {
var element = document.body;
element.classList.toggle("dark-mode");
}
body{background:white; color:black; transition:0.3; }
.dark-mode{color:white; transition:0.3s; background:black;}
<button onclick="change()">dark</button>
<p>Some text</p>
答案 0 :(得分:0)
您从没使用过它的事实,即使您下次再说……也不是没有借口的借口。
文档和用法很简单。
function change() {
var element = document.body;
element.classList.toggle("dark-mode");
if (element.classList.contains("dark-mode")) {
//if class was added to body
localStorage.setItem("background", "dark-mode");
//save information in "background" localStorage variable, use dark-mode class name
} else {
localStorage.setItem("background", "");
//if class was removed set background" localStorage variable to null
}
}
document.addEventListener("DOMContentLoaded", function(event) {
//when loading document
var background = localStorage.getItem("background");
// get localStorage var background
if (background) {
// if its not null and empty
document.body.className += background;
//add class to body
}
});
答案 1 :(得分:0)
像Mohit / ikiK一样,您需要使用条件浏览器并检查浏览器的localStorage,请记住:
localStorage.getItem(keyName):获取存储在浏览器存储中的值
localStorage.setItem(keyName,value):为浏览器存储设置一个值