英文:
Dark mode gets turned off on refresh a page
问题
My page not load dark mode when it refresh.
const dayNight = document.querySelector(".day-night");
dayNight.addEventListener("click", () => {
dayNight.querySelector("i").classList.toggle("fa-sun");
dayNight.querySelector("i").classList.toggle("fa-moon");
document.body.classList.toggle("dark");
});
window.addEventListener("load", () => {
if (document.body.classList.contains("dark")) {
dayNight.querySelector("i").classList.add("fa-sun");
} else {
dayNight.querySelector("i").classList.add("fa-moon");
}
})
英文:
my page not load darkmode when it refresh
const dayNight = document.querySelector(".day-night");
dayNight.addEventListener("click", () => {
dayNight.querySelector("i").classList.toggle("fa-sun");
dayNight.querySelector("i").classList.toggle("fa-moon");
document.body.classList.toggle("dark");
});
window.addEventListener("load", () => {
if (document.body.classList.contains("dark")) {
dayNight.querySelector("i").classList.add("fa-sun");
} else {
dayNight.querySelector("i").classList.add("fa-moon");
}
})
答案1
得分: 2
你可以使用LocalStorage来持久保存数据。
const dayNight = document.querySelector(".day-night");
dayNight.addEventListener("click", () => {
dayNight.querySelector("i").classList.toggle("fa-sun");
dayNight.querySelector("i").classList.toggle("fa-moon");
const isDark = document.body.classList.toggle("dark");
// 本地持久化
localStorage.setItem("dark", isDark);
});
window.addEventListener("load", () => {
const isDark = localStorage.getItem("dark");
if (isDark === "true") {
document.body.classList.add("dark");
dayNight.querySelector("i").classList.add("fa-moon");
} else {
document.body.classList.remove("dark");
dayNight.querySelector("i").classList.add("fa-sun");
}
})
你还可以查看@media prefers-color-scheme css 媒体特性,以根据用户系统的首选项检测颜色模式。
英文:
You can use LocalStorage to persist the data.
const dayNight = document.querySelector(".day-night");
dayNight.addEventListener("click", () => {
dayNight.querySelector("i").classList.toggle("fa-sun");
dayNight.querySelector("i").classList.toggle("fa-moon");
const isDark = document.body.classList.toggle("dark");
// Persist this locally
localStorage.setItem("dark", isDark);
});
window.addEventListener("load", () => {
const isDark = localStorage.getItem("dark");
if (isDark === "true") {
document.body.classList.add("dark");
dayNight.querySelector("i").classList.add("fa-moon");
} else {
document.body.classList.remove("dark");
dayNight.querySelector("i").classList.add("fa-sun");
}
})
You can also checkout @media prefers-color-scheme css media feature to detect it with respect to user's system preferences.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论