1

我正在尝试为我的网站创建暗模式。我已经找到了如何进行系统偏好切换以及如何使用按钮覆盖它并将其设置为本地存储。但是我很难像改变身体一样改变body2。这是我的代码,我希望你能帮助我用一个按钮改变两个元素的颜色。我也想实现 body2 的颜色变化。谢谢!HTML:

<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="icon" type="image/ico" href="img/favicon.ico">
    <link rel="stylesheet" href="css/main.css">

</head>

<body>
</div>
<div class="heading">
    <button class="tile"><span class="tooltip">
    </button>
</div>
<div class="body2" id="body2" onclick="closeMenu()">
<script src="js/main.js"></script>
</body>

</html>

JS:

const btn = document.querySelector(".tile");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
const currentTheme = localStorage.getItem("theme");
if (currentTheme === "dark") {
    document.body.classList.toggle("dark-mode");
} else if (currentTheme === "light") {
    document.body.classList.toggle("light-mode");
}

btn.addEventListener("click", function () {
    if (prefersDarkScheme.matches) {
        document.body.classList.toggle("light-mode");
        var theme = document.body.classList.contains("light-mode")
            ? "light"
            : "dark";
    } else {
        document.body.classList.toggle("dark-mode");
        var theme = document.body.classList.contains("dark-mode")
            ? "dark"
            : "light";
    }
    localStorage.setItem("theme", theme);
});

CSS:

body{
    --bkg:mintcream;
}
body.dark-mode{
    --bkg: url("../img/background.jpg") no-repeat, #1a2022;
}

.body2{
    --text-color: black;
    --bkg2: rgba(245, 245, 245, 0.8);
}

.body2.dark-mode2{
    --text-color: white;
    --bkg2:rgba(37, 44, 46, 0.7);
}
@media (prefers-color-scheme: dark) {
body{
    --bkg: #1a2022;
}
body.light-mode{
    --bkg:mintcream;
}

.body2{
    --text-color: white;
    --bkg2: rgba(37, 44, 46, 0.7) ;
}

.body2.light-mode2{
    --text-color: black;
    --bkg:rgba(245, 245, 245, 0.8);
}
}
body{
    margin: 0;
    background: var(--bkg);
    transition: color, background-color .5s;
}
.body2 {
    font-size: 1.8em;
    text-align: center;
    margin: 0 10% 0 10%;
    padding: 10px 30px 10px 30px;
    height: max-content;
    background: var(--bkg2);
    color: var(--text-color);
    transition: background-color .5s ease;
}
4

1 回答 1

0

我不确定,为什么它没有更早地工作,但经过几次尝试添加const body2 = body2.getElementById("body2");和添加body2.classlist.toggle("light-mode2");body2.classlist.toggle("dark-mode2");document.body.classlist.toggle("light-mode");document.body.classlist.toggle("dark-mode");为我工作。

于 2021-04-26T09:20:57.787 回答