因此,我有几个网页,并希望他们保持黑暗,如果黑暗模式是在另一个页面上打开。因此,我在我的所有HTML文件中添加了一个js脚本,但它根本不起作用。在此之后,我尝试将这个脚本添加到一个HTML文件中,在重新加载页面后,它一直处于黑暗状态,但很明显,它并没有影响其他页面。我如何改变脚本使其工作,问题在哪里?
剧本:
if(localStorage.getItem("theme")==null){
localStorage.setItem("theme", "light");
}
let localData = localStorage.getItem("theme");
if (localData == "light") {
icon.src = "images/moon.png";
document.body.classList.remove("dark-theme");
}
else if (localData == "dark") {
icon.src = "images/sun.png";
document.body.classList.add("dark-theme");
}
icon.onclick = function () {
document.body.classList.toggle("dark-theme");
if (document.body.classList.contains("dark-theme")) {
icon.src = "images/sun.png";
localStorage.setItem("theme", "dark");
}
else {
icon.src = "images/moon.png";
localStorage.setItem("theme", "light");
}
} ``` 发布于 2022-06-01 21:19:30
请确保您的<script>是在body标记(https://stackoverflow.com/a/9916754/18667225)之后定义的。检查F12-控制台中的错误!在F12网络存储选项卡中,您还可以检查密钥的状态。
在Firefox中,这个简化的代码适用于我:
<!DOCTYPE html>
<html>
<head>
</head>
<body onclick=toggle_theme()>
Hello World!
<body>
<script>
if (localStorage.getItem("theme")==null){
localStorage.setItem("theme", "light");
}
let localData = localStorage.getItem("theme");
if (localData == "light") {
alert("moon pre");
document.body.classList.remove("dark-theme");
}
else if (localData == "dark") {
alert("sun pre");
document.body.classList.add("dark-theme");
}
function toggle_theme() {
document.body.classList.toggle("dark-theme");
if (document.body.classList.contains("dark-theme")) {
alert("sun");
localStorage.setItem("theme", "dark");
}
else {
alert("moon");
localStorage.setItem("theme", "light");
}
}
</script>
</html>https://stackoverflow.com/questions/72467937
复制相似问题