项目主题切换切换
290字小于1分钟
2024-06-24
主题风格切换
场景很简单:
- 用户在页面中点击按钮, 切换主题风格
- 主题风格切换后, 页面中所有使用到主题颜色的地方, 都需要重新渲染
方案一: css变量 + 类名切换
1. 定义公共主题变量
:root {
--theme-color: #fff;
--theme-bg-color: #f5f5f5;
--theme-font-color: #333;
}2. 定义不同主题类名的变量
.theme-dark {
--theme-color: #333;
--theme-bg-color: #f5f5f5;
--theme-font-color: #fff;
}3. 切换类名
const themeBtn = document.querySelector(".theme-btn");
const body = document.querySelector("body");
themeBtn.addEventListener("click", () => {
body.classList.toggle("theme-dark");
});4. 使用变量
body {
color: var(--theme-font-color);
background-color: var(--theme-bg-color);
}方案二: css变量 + 类名切换 + js动态设置
1. 定义公共主题变量
:root {
--theme-color: #fff;
--theme-bg-color: #f5f5f5;
--theme-font-color: #333;
}2. 定义类名
// theme-dark.js文件
export default {
"--theme-color": #333;
"--theme-bg-color": #f5f5f5;
"--theme-font-color": #fff;
}3. 切换类名 动态设置
import themeDark from "./theme-dark";
const themeBtn = document.querySelector(".theme-btn");
const body = document.querySelector("body");
const root = document.querySelector(":root");
themeBtn.addEventListener("click", () => {
body.classList.toggle("theme-dark");
for (const key in themeDark) {
root.style.setProperty(key, themeDark[key]);
}
});4. 使用变量
body {
color: var(--theme-font-color);
background-color: var(--theme-bg-color);
}