我正在创建一个暗模式布局,并且除了一个似乎无法找到的小错误之外,我都能正常工作。我的黑暗模式正在检查一些事情:
应用暗模式后,用户刷新页面时,暗模式仍然存在,并且可以正常工作。但是,该复选框不会取消选中。 localstorage键/值对更改为“ light”,因此可以正常工作。某个东西破坏了我的复选框,或将其保留在checkbox.checked = true
上。
const darkMode = () => {
const page = document.querySelector("#page");
const systemDarkMode = window.matchMedia("(prefers-color-scheme: dark)");
const checkbox = document.querySelector("#dark-mode-select");
const label = document.querySelector("#dark-mode-label");
let theme = window.localStorage.getItem("theme");
let preference; //initialize variable
//Find the system preference of the OS:
const findSystemPreference = () => {
if (systemDarkMode.matches) {
preference = "dark";
} else {
preference = "light";
}
setTheme(preference);
};
//Listen for click event, and if checkbox is true, set dark appearance & local storage:
const setUserPreference = (e) => {
if (e.target.checked == true) {
preference = "dark";
window.localStorage.setItem("theme", "dark");
} else if (e.target.checked == false) {
preference = "light";
window.localStorage.setItem("theme", "light");
}
setTheme(preference);
};
//Set theme: I believe my bug lies somewhere in here. Goal is to check if the preference variable is dark or light, OR is there's a localStorage theme
const setTheme = (pref) => {
if (pref === "dark" || theme === "dark") {
checkbox.checked = true;
page.classList.add("dark-mode");
label.textContent = "Dark Mode Is On";
} else {
page.classList.remove("dark-mode");
label.textContent = "Dark Mode Is Off";
checkbox.checked = false;
}
};
checkbox.addEventListener("click", setUserPreference);
window.addEventListener("DOMContentLoaded", findSystemPreference);
};
我尝试添加更具体的逻辑,例如添加`else if(pref ===“ light” || theme ===“ dark”),但这仍然行不通。
我可以将检查语句分解为单独的函数,如下所示:
const check = () => {
checkbox.checked = true;
page.classList.add("dark-mode");
label.textContent = "Dark Mode Is On";
};
const uncheck = () => {
page.classList.remove("dark-mode");
label.textContent = "Dark Mode Is Off";
checkbox.checked = false;
};
结合:
const findSystemPreference = () => {
if (systemDarkMode.matches) {
preference = "dark";
check();
} else {
preference = "light";
uncheck();
}
};
但是我不知道将if(theme === "dark")
语句放在哪里不会破坏我的复选框
答案 0 :(得分:1)
错误在这里
if (pref === "dark" || theme === "dark") {
您的theme
变量始终设置为dark
,因为它从localStorage
检索了该值,我认为删除theme === "dark"
都应该起作用
编辑:您应该从if语句中删除该条件,并在所有内容之外,创建一个包含if条件功能的函数
const setCheckboxChecked = () => { // change name and you can even abstract this function to use to set the checkbox to true/false, update text, etc.
checkbox.checked = true;
page.classList.add("dark-mode");
label.textContent = "Dark Mode Is On";
}
此功能应替换为:
const findSystemPreference = () => {
if (systemDarkMode.matches) {
preference = "dark";
} else {
preference = "light";
}
setCheckboxChecked()
};
我想做的是仅将复选框设置为true一次,并从if中删除该条件,因为theme
始终是相同的值,因此始终解析为true
或{{ 1}}