html主题切换小demo
主题切换功能为网页和应用程序提供了多样化的视觉风格与使用体验。实现多主题切换的技术方案丰富多样,其中 CSS 变量和 JavaScript 样式控制是较为常见的实现方式。
以下是一个简洁的多主题切换示例,愿它能为您的编程之旅增添一份趣味。
代码展示
<!DOCTYPE html>
<html lang="zh">
<head><meta charset="UTF-8"><title>多主题切换 Demo</title><style>:root {--bg-color: #ffffff;--text-color: #000000;}body {background-color: var(--bg-color);color: var(--text-color);font-family: sans-serif; /* 字体 */text-align: center; /* 居中对齐 */transition: background-color 0.3s, color 0.3s; /* 过渡效果 */padding-top: 100px; /* 顶部内边距 */}.dark-theme { /* 暗黑主题 */--bg-color: #121212; /* 背景色 */--text-color: #eeeeee; /* 文字色 */}.blue-theme { /* 蓝色主题 */--bg-color: #e3f2fd;--text-color: #1565c0;}.green-theme { /* 绿色主题 */--bg-color: #e8f5e9;--text-color: #2e7d32;}.red-theme { --bg-color: #ffebee; --text-color: #c62828; }.purple-theme { --bg-color: #f3e5f5; --text-color: #6a1b9a; }.orange-theme { --bg-color: #fff3e0; --text-color: #ef6c00; }.gray-theme { --bg-color: #f5f5f5; --text-color: #424242; }select, button {padding: 10px 20px;font-size: 16px;margin-top: 20px;cursor: pointer;}</style>
</head>
<body><h1>选择主题</h1><p>这是个主题是 <span id="currentTheme">默认</span></p><select id="themeSelector" onchange="changeTheme()"><option value="">默认</option><option value="dark-theme">暗黑</option><option value="blue-theme">蓝色</option><option value="green-theme">绿色</option><option value="red-theme">红色</option><option value="purple-theme">紫色</option><option value="orange-theme">橙色</option><option value="gray-theme">灰色</option></select><script>function changeTheme() {const theme = document.getElementById('themeSelector').value;document.body.className = theme;const themeName = theme ? theme.split('-')[0] : '默认';document.getElementById('currentTheme').textContent = themeName;}</script>
</body>
</html>
效果展示
实现原理解析
该 demo 的核心思想是通过 CSS标签引入不同的样式,并使用 JavaScript 修改其 href
属性,从而实现动态更换主题的功能。这种方式简单直观,适用于中小型项目或学习用途。
扩展建议
如果你希望进一步优化这个功能,可以考虑以下几点:
-
使用
localStorage
记住用户选择的主题; -
使用 CSS 变量搭配类名控制,减少重复代码;
-
使用框架(如 Vue/React)时结合组件化设计进行封装;
-
添加动画过渡效果,提升用户体验。