用js实现换肤
使用CSS变量实现换肤
通过CSS变量(Custom Properties)可以轻松实现换肤功能。定义不同主题的颜色变量,通过JavaScript切换这些变量。
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--text-color: #333;
}
.dark-theme {
--primary-color: #2980b9;
--secondary-color: #27ae60;
--text-color: #fff;
}
function toggleTheme() {
document.body.classList.toggle('dark-theme');
}
使用类名切换主题
为不同主题创建独立的CSS类,通过JavaScript动态添加或移除这些类来改变样式。
.light-theme {
background-color: #fff;
color: #333;
}
.dark-theme {
background-color: #333;
color: #fff;
}
function switchTheme(themeName) {
document.body.className = themeName;
}
使用localStorage保存主题偏好
结合localStorage可以实现用户选择的主题持久化,下次访问时自动应用上次选择的主题。
function setTheme(themeName) {
localStorage.setItem('theme', themeName);
document.body.className = themeName;
}
function loadTheme() {
const theme = localStorage.getItem('theme');
if (theme) {
setTheme(theme);
}
}
// 页面加载时应用保存的主题
window.addEventListener('DOMContentLoaded', loadTheme);
动态加载CSS文件
对于复杂的主题系统,可以创建不同的CSS文件,通过JavaScript动态加载对应的样式表。
function loadThemeCSS(themeName) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = `themes/${themeName}.css`;
document.head.appendChild(link);
}
响应式主题切换
结合CSS媒体查询和JavaScript,可以实现根据系统偏好自动切换主题。
@media (prefers-color-scheme: dark) {
:root {
--primary-color: #2980b9;
--secondary-color: #27ae60;
--text-color: #fff;
}
}
function detectSystemTheme() {
const darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
return darkMode ? 'dark' : 'light';
}
function applySystemTheme() {
const theme = detectSystemTheme();
setTheme(theme);
}
window.matchMedia('(prefers-color-scheme: dark)').addListener(applySystemTheme);






