用js实现换肤
使用 CSS 变量实现换肤
通过定义 CSS 变量并在 JavaScript 中动态修改这些变量,可以轻松实现换肤功能。CSS 变量具有全局性,修改后所有引用该变量的元素都会更新。
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--text-color: #333;
}
body {
background-color: var(--primary-color);
color: var(--text-color);
transition: all 0.3s ease;
}
button {
background-color: var(--secondary-color);
border: none;
padding: 10px 20px;
color: white;
cursor: pointer;
}
</style>
</head>
<body>
<h1>换肤功能演示</h1>
<button onclick="changeTheme('light')">浅色主题</button>
<button onclick="changeTheme('dark')">深色主题</button>
<button onclick="changeTheme('blue')">蓝色主题</button>
<script>
function changeTheme(theme) {
const root = document.documentElement;
switch(theme) {
case 'light':
root.style.setProperty('--primary-color', '#f5f5f5');
root.style.setProperty('--secondary-color', '#e0e0e0');
root.style.setProperty('--text-color', '#333');
break;
case 'dark':
root.style.setProperty('--primary-color', '#222');
root.style.setProperty('--secondary-color', '#444');
root.style.setProperty('--text-color', '#fff');
break;
case 'blue':
root.style.setProperty('--primary-color', '#3498db');
root.style.setProperty('--secondary-color', '#2980b9');
root.style.setProperty('--text-color', '#fff');
break;
}
}
</script>
</body>
</html>
使用类名切换实现换肤
另一种方法是为不同主题定义不同的 CSS 类,然后通过 JavaScript 切换这些类。
<!DOCTYPE html>
<html>
<head>
<style>
body {
transition: all 0.3s ease;
}
.light-theme {
background-color: #f5f5f5;
color: #333;
}
.dark-theme {
background-color: #222;
color: #fff;
}
.blue-theme {
background-color: #3498db;
color: #fff;
}
button {
padding: 10px 20px;
cursor: pointer;
}
.light-theme button {
background-color: #e0e0e0;
}
.dark-theme button {
background-color: #444;
}
.blue-theme button {
background-color: #2980b9;
}
</style>
</head>
<body class="light-theme">
<h1>换肤功能演示</h1>
<button onclick="changeTheme('light-theme')">浅色主题</button>
<button onclick="changeTheme('dark-theme')">深色主题</button>
<button onclick="changeTheme('blue-theme')">蓝色主题</button>
<script>
function changeTheme(theme) {
document.body.className = theme;
}
</script>
</body>
</html>
使用 localStorage 保存主题偏好
为了在页面刷新后保持用户选择的主题,可以将主题信息存储在 localStorage 中。
// 在页面加载时检查保存的主题
document.addEventListener('DOMContentLoaded', function() {
const savedTheme = localStorage.getItem('theme') || 'light-theme';
document.body.className = savedTheme;
});
function changeTheme(theme) {
document.body.className = theme;
localStorage.setItem('theme', theme);
}
响应系统主题变化
可以检测用户设备的主题偏好(深色/浅色模式)并自动应用相应主题。

// 检测系统主题偏好
const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)');
// 监听系统主题变化
prefersDarkScheme.addListener(e => {
if (e.matches) {
changeTheme('dark-theme');
} else {
changeTheme('light-theme');
}
});
// 初始加载时检查
if (prefersDarkScheme.matches) {
changeTheme('dark-theme');
} else {
changeTheme('light-theme');
}
以上方法可以根据项目需求选择使用,CSS 变量方法更适合复杂的主题系统,而类名切换方法更简单直接。结合 localStorage 可以提升用户体验,记住用户的主题偏好。






