js实现换肤
使用CSS变量实现换肤
通过CSS变量可以轻松实现主题切换功能。CSS变量在根元素中定义,通过JavaScript动态修改这些变量值。
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--text-color: #333;
}
.dark-theme {
--primary-color: #2980b9;
--secondary-color: #27ae60;
--text-color: #fff;
}
JavaScript切换主题代码:
function toggleTheme() {
document.body.classList.toggle('dark-theme');
}
使用类名切换实现换肤
通过为不同主题创建对应的CSS类,切换body元素的类名来改变主题。
.light-theme {
background: #fff;
color: #333;
}
.dark-theme {
background: #222;
color: #fff;
}
JavaScript切换代码:
function setTheme(themeName) {
document.body.className = themeName;
}
使用localStorage持久化主题
结合localStorage可以保存用户选择的主题,下次访问时自动加载。
function saveTheme(themeName) {
localStorage.setItem('theme', themeName);
document.body.className = themeName;
}
// 页面加载时检查保存的主题
window.addEventListener('DOMContentLoaded', () => {
const savedTheme = localStorage.getItem('theme') || 'light-theme';
document.body.className = savedTheme;
});
动态加载CSS文件实现换肤
对于大型项目,可以为不同主题创建单独的CSS文件,动态加载所需样式表。
function loadTheme(themeName) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = `themes/${themeName}.css`;
document.head.appendChild(link);
// 移除旧主题
const oldTheme = document.querySelector('link[data-theme]');
if(oldTheme) oldTheme.remove();
link.setAttribute('data-theme', themeName);
}
使用CSS预处理器变量
如果项目使用Sass/Less等预处理器,可以生成多套主题CSS文件。
Sass示例:
$themes: (
light: (
bg: #fff,
text: #333
),
dark: (
bg: #222,
text: #fff
)
);
@mixin theme() {
@each $theme, $map in $themes {
.#{$theme}-theme {
$theme-map: () !global;
@each $key, $submap in $map {
$value: map-get($map, $key);
$theme-map: map-merge($theme-map, ($key: $value)) !global;
}
@content;
$theme-map: null !global;
}
}
}
@function themed($key) {
@return map-get($theme-map, $key);
}






