需要在html节点添加自定义属性,并根据当前主题色通过CSS变量控制。
点击切换按钮后设置自定义属性值即可。
根据切换html元素的自定义属性来改变样式
/* 浅色模式 */
html[data-theme="light"]:root {
--body-background: #efefef;
}
/* 深色模式 */
html[data-theme="dark"]:root {
--body-background: #000;
}
body {
background: var(--body-background);
transition: background 0.3s;
}
js中点击按钮切换html元素的自定义属性
const htmlEl = document.documentElement;
const buttonEl = document.getElementById("btn");
buttonEl.addEventListener("click", () => {
const currentTheme = htmlEl.getAttribute("data-theme");
const nextTheme = currentTheme === "dark" ? "light" : "dark";
htmlEl.setAttribute("data-theme", nextTheme);
});