主題切換功能為網頁和應用程序提供了多樣化的視覺風格與使用體驗。實現多主題切換的技術方案豐富多樣,其中 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)時結合組件化設計進行封裝;
-
添加動畫過渡效果,提升用戶體驗。