js实现换肤
实现方法一:CSS变量切换
通过定义CSS变量并在JavaScript中动态修改变量值实现换肤效果。
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--text-color: #333;
}
.dark-theme {
--primary-color: #2980b9;
--secondary-color: #27ae60;
--text-color: #f5f5f5;
}
function toggleTheme() {
document.body.classList.toggle('dark-theme');
}
// 初始加载时检查本地存储
if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark-theme');
}
实现方法二:类名切换
定义不同主题的CSS类,通过切换类名实现换肤。
.light-theme {
background-color: #fff;
color: #333;
}
.dark-theme {
background-color: #222;
color: #f5f5f5;
}
function switchTheme(themeName) {
document.body.className = themeName + '-theme';
localStorage.setItem('theme', themeName);
}
// 初始化主题
const savedTheme = localStorage.getItem('theme') || 'light';
switchTheme(savedTheme);
实现方法三:动态加载CSS文件
通过动态创建link元素加载不同的CSS文件实现换肤。
function loadTheme(themeName) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = `themes/${themeName}.css`;
link.id = 'theme-style';
const oldLink = document.getElementById('theme-style');
if (oldLink) {
document.head.removeChild(oldLink);
}
document.head.appendChild(link);
localStorage.setItem('theme', themeName);
}
// 初始化加载主题
const currentTheme = localStorage.getItem('theme') || 'default';
loadTheme(currentTheme);
实现方法四:使用CSS预处理器变量
结合Sass/Less等预处理器和JavaScript实现换肤。

$themes: (
light: (
bg: #fff,
text: #333,
primary: #3498db
),
dark: (
bg: #222,
text: #f5f5f5,
primary: #2980b9
)
);
function applyTheme(theme) {
Object.keys(theme).forEach(key => {
document.documentElement.style.setProperty(
`--${key}`,
theme[key]
);
});
}
// 切换主题示例
const themes = {
light: {
'bg': '#fff',
'text': '#333',
'primary': '#3498db'
},
dark: {
'bg': '#222',
'text': '#f5f5f5',
'primary': '#2980b9'
}
};
applyTheme(themes.dark);
注意事项
- 主题切换时考虑添加过渡动画提升用户体验
- 使用localStorage保存用户选择的主题
- 提供系统主题偏好检测功能
- 确保所有页面元素都能正确响应主题变化
- 高对比度主题需要考虑可访问性需求






