1

嗨,我在将我的网站上的暗模式设置保存到 时遇到问题localStorage,因此在刷新或转换到另一个页面后,设置将保持不变。不需要基于用户偏好的自动更改。实际上,我有 2 个具有不同颜色的主体和一个根据明暗设置而变化的图标。

JS:

var ImgSource = ["img/ModeDark.png", "img/ModeLight.png"];
var Index = 0;

function changeColor() {
    var body2 = document.getElementById("body2");
    var img = document.getElementById("DarkMode");
    document.body.classList.toggle("bodyDark");
    body2.classList.toggle("body2Dark");
    document.body.classList.toggle("body");
    body2.classList.toggle("body2");
    if (Index >= ImgSource.length) {
        Index = 0;
    }
    img.src = ImgSource[Index];
    Index++;
}

localStorage.setItem("dark", document.body.classList.contains("bodyDark") ? "bodyDark" : "body");
localStorage.setItem("dark2", document.body.classList.contains("body2Dark") ? "body2Dark" : "body2");

if (localStorage.getItem("dark") === "bodyDark") {
    changeColor();
} else if (
    localStorage.getItem("dark") !== "body") {
    changeColor();
}

if (localStorage.getItem("dark2") === "body2Dark") {
    changeColor();
} else if (
    localStorage.getItem("dark2") !== "body2") {
    changeColor();
}

CSS:

body {
    background-color: mintcream;
    transition: color, background-color .5s;
    margin: 0;
    color: black;
}

.bodyDark {
    background-color: #1a2022;
    transition: color, background-color .5s;
    margin: 0;
    color: white;
}
.body2 {
    font-size: 22px;
    text-align: center;
    line-height: 1.3;
    margin: 0 10% 0 10%;
    padding: 10px 30px 10px 30px;
    height: max-content;
    transition: background-color .5s ease;
    background-color: #f5f5f5;
    color: black;
}

.body2Dark {
    font-size: 22px;
    text-align: center;
    line-height: 1.3;
    margin: 0 10% 0 10%;
    padding: 10px 30px 10px 30px;
    height: max-content;
    transition: background-color .5s;
    background-color: #252c2e;
    color: white;
}

HTML:

<body>
    <div class="heading">
        <button class="tile" onclick="changeColor()"><img id="DarkMode" alt="DarkMode" src="img/ModeLight.png" width="25"/>
        </button>
    </div>
    <div class="body2" id="body2">
        <h1>AAAAAAAA</h1>
        <br>
        <p>Paragraph 1</p>
        <br>
        <br>
    </div>
</body>

非常感谢!!

4

0 回答 0