在前端实现主题切换功能,通常涉及到CSS样式的管理和JavaScript的动态应用。本文将介绍通过使用CSS变量的方法来实现主题切换功能。
html代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>theme</title>
<style>
* {
margin: 0;
padding: 0;
}
:root {
--color-primary: #1890ff;
--bg-body: #fff;
--color-text: #333;
}
:root[data-theme="dark"] {
--color-primary: #52c41a;
--bg-body: #1a1a1a;
--color-text: #e6e6e6;
}
:root[data-theme="light"] {
--color-primary: #ff66ff;
--bg-body: #fff7e6;
--color-text: #696969;
}
</style>
<style>
.btn {
background: var(--color-primary);
}
body {
background: var(--bg-body);
color: var(--color-text);
transition: background 0.3s;
}
</style>
</head>
<body>
<div id="js_btn" class="btn">主题</div>
<div>theme</div>
</body>
</html>
js代码如下:
const btn = document.getElementById('js_btn');
btn.onclick = () => {
updateTheme();
};
const toggleTheme = (themeName) => {
document.documentElement.setAttribute('data-theme', themeName);
themeName && localStorage.setItem('_THEME_', themeName);
};
const updateTheme = (isInit = false) => {
const currentTheme = localStorage.getItem('_THEME_');
if (isInit) {
toggleTheme(currentTheme);
return;
}
const savedTheme = currentTheme == 'light' ? 'dark' : 'light';
toggleTheme(savedTheme);
};
updateTheme(true);