我有这个简单的代码,可以将网页设置为暗/亮模式。例如,它在您当前的页面上运行良好,但是如果我单击任何链接或按钮将我从index.html
重定向到test.html
,则设置将重置为默认值。假设我想以浅色模式浏览我的页面,然后点击test button
可以回到黑暗模式。
如何使自己记住保持选择的相同模式?这就是我得到的。
Index.html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Dark -Light Mode Switcher</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<body id="body" class="dark-mode">
<h1>Dark/Light Mode Switcher</h1>
<button type="button" name="dark_light" onclick="toggleDarkLight()" title="Toggle dark/light mode">?
</button>
<p><a href="test.html"><button name="test">TEST PAGE</font></button></a>
<!-- partial -->
<script src="./script.js"></script>
</body>
</html>
Script.js
function toggleDarkLight() {
var body = document.getElementById("body");
var currentClass = body.className;
body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
}
Style.css
body.dark-mode {
background-color: #111;
color: #eee;
}
body.dark-mode a {
color: #111;
}
body.dark-mode button {
background-color: #eee;
color: #111;
}
body.light-mode {
background-color: #eee;
color: #111;
}
body.light-mode a {
color: #111;
}
body.light-mode button {
background-color: #111;
color: #eee;
}
答案 0 :(得分:1)
如果按如下所示更新Script.js,则将获得所需的内容:
body.className=localStorage.getItem("stateMode");
function toggleDarkLight() {
var body = document.getElementById("body");
var currentClass = body.className;
body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
localStorage.setItem("stateMode",body.className);
}