是否可以进入深色模式并在切换页面后仅使用一个 js 文件保持深色模式?

Is it possible to enter dark mode and after switching pages dark mode stays on with only one js file?

所以,我有几个网页,如果在另一个页面上打开暗模式,我希望它们保持暗。因此,我向所有 HTML 文件添加了一个 js 脚本,但它根本不起作用。在那之后,我尝试将这个脚本添加到一个 HTML-file 中,并且在重新加载页面后它仍然是黑暗的,但是,很明显,它没有影响其他页面。 我怎样才能更改脚本以使其正常工作,问题出在哪里?
脚本:


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");
    }
} ``` 

请确保您的 <script> 是在 body 标签 () 之后定义的。检查 F12-Console 中的错误!在 F12 Web-Storage 选项卡中,您还可以检查密钥的状态。

这个简化的代码在 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>