【问题标题】:Toggle two classes from local storage从本地存储切换两个类
【发布时间】:2021-07-19 06:01:00
【问题描述】:

我正在尝试为我的网站创建暗模式。我发现了如何进行系统偏好切换以及如何用按钮覆盖它+将其设置为本地存储。但是我很难像改变身体一样改变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;
}

【问题讨论】:

    标签: javascript local-storage darkmode


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      相关资源
      最近更新 更多