从本地存储切换两个类



我正在尝试为我的网站创建一个黑暗模式。我已经了解了如何进行系统首选项切换,以及如何用按钮覆盖它并将其设置为本地存储。但我很难像改变身体一样改变身体。这是我的代码,我希望你能帮助我用一个按钮改变两个元素的颜色。我也想为body2实现颜色的更改。Thx!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;
}

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

最新更新