我试图实现的图标的变化和停留,如果darkmode被激活,即.如果黑暗模式为真,图标将为太阳黑暗模式为假,图标为月亮。
但是,在重新加载页面之后,页面本身仍然处于黑暗模式,因为它存储在本地存储中,但图标会变回。
换句话说,我想要达到的是
darkmode = enabled then icon sun darkmode = null the icon moon
<button
id="dark-mode-toggle"
class="dark-mode-toggle"
area-label="toggle dark mode"
>
<i class="bx bx-moon moon" id="moon"></i>
<i class="bx bx-sun sun" id="sun"></i>
</button>
/* Darkmode */
.dark-mode-toggle {
background: transparent;
border: none;
cursor: pointer;
}
#moon {
color: var(--a-clr);
font-size: 2rem;
display: block;
}
#sun {
font-size: 2rem;
color: var(--a-clr);
display: block;
}
let darkMode = localStorage.getItem("darkMode");
const sun = document.getElementById("sun");
const moon = document.getElementById("moon");
const darkModeToggle = document.querySelector("#dark-mode-toggle");
const enableDarkMode = () => {
document.documentElement.classList.add("darkmode");
localStorage.setItem("darkMode", "enabled");
};
const disableDarkMode = () => {
document.documentElement.classList.remove("darkmode");
localStorage.setItem("darkMode", null);
};
darkModeToggle.addEventListener("click", () => {
darkMode = localStorage.getItem("darkMode");
if (darkMode !== "enabled") {
enableDarkMode();
} else {
disableDarkMode();
}
});
谢谢你!
1条答案
按热度按时间insrf1ej1#
您需要从
darkMode
初始更新图标的状态尝试将其添加到JavaScript中。