使用Javascript document.body.className添加body类,而不是document.body.setAttribute
我正在使用下面的函数在CSS中切换暗模式。它使用使用Javascript document.body.className添加body类,而不是document.body.setAttribute,javascript,html,css,local-storage,addeventlistener,Javascript,Html,Css,Local Storage,Addeventlistener,我正在使用下面的函数在CSS中切换暗模式。它使用document.body.setAttribute将属性data-theme=“dark”添加到文档正文标记中,并在再次切换时将其删除;该函数读取和/或设置localStoragedarkSwitch,以在页面加载之间保持暗模式状态。CSS就是[data theme=“dark”].myselector{background color:#000;} 功能: <input type="checkbox" class=&q
document.body.setAttribute
将属性data-theme=“dark”
添加到文档正文标记中,并在再次切换时将其删除;该函数读取和/或设置localStoragedarkSwitch
,以在页面加载之间保持暗模式状态。CSS就是[data theme=“dark”].myselector{background color:#000;}
功能:
<input type="checkbox" class="custom-control-input" id="darkSwitch" /> // Simply the button to toggle
(function() {
var darkSwitch = document.getElementById("darkSwitch");
if (darkSwitch) {
initTheme();
darkSwitch.addEventListener("change", function(event) {
resetTheme();
});
function initTheme() {
var darkThemeSelected =
localStorage.getItem("darkSwitch") !== null &&
localStorage.getItem("darkSwitch") === "dark";
darkSwitch.checked = darkThemeSelected;
darkThemeSelected
? document.body.setAttribute("data-theme", "dark")
: document.body.removeAttribute("data-theme");
}
function resetTheme() {
if (darkSwitch.checked) {
document.body.setAttribute("data-theme", "dark");
localStorage.setItem("darkSwitch", "dark");
} else {
document.body.removeAttribute("data-theme");
localStorage.removeItem("darkSwitch");
}
}
}
})();
className
不是一个函数。你把它和类列表
混淆了。类列表也不是。我想你想要更接近的东西吧?document.body.className=“dark”:document.body.className=document.body.className.replace(“深色”)但是,在进行替换时,我认为使用classList.remove()更容易
@user1599011谢谢,这对classList.remove很有意思;想添加一个示例吗?而不是document.body.className=document.body.className.replace(“深色”和“”)
,我会使用document.body.classList.remove(“暗”)
前者还将替换任何部分匹配。例如,class=“darkPage”
将变成class=“Page”
className
只是将其作为字符串处理,而classList
处理列表方面。
(function() {
var darkSwitch = document.getElementById("darkSwitch");
if (darkSwitch) {
initTheme();
darkSwitch.addEventListener("change", function(event) {
resetTheme();
});
function initTheme() {
var darkThemeSelected =
localStorage.getItem("darkSwitch") !== null &&
localStorage.getItem("darkSwitch") === "dark";
darkSwitch.checked = darkThemeSelected;
darkThemeSelected
? document.body.className("dark")
: document.body.className.replace("dark","");
}
function resetTheme() {
if (darkSwitch.checked) {
document.body.className("dark");
localStorage.setItem("darkSwitch", "dark");
} else {
document.body.className.replace("dark","");
localStorage.removeItem("darkSwitch");
}
}
}
})();