html
<!DOCTYPE html>
<html>
<head><title>主题切换示例</title>
</head>
<body><div class="app"><button id="themeButton">切换主题</button><div class="content"><h1>主题切换示例</h1><p>当前主题:<span id="themeText">light</span></p><p>这是一些内容,样式根据主题变化。</p></div></div>
</body>
</html>
css
:root {--primary-color-light: #3498db;--primary-color-dark: #e74c3c;
}/* 默认主题样式 */
html[data-theme='light'] {--primary-color: var(--primary-color-light);background-color: #fff;color: #333;
}/* 暗主题样式 */
html[data-theme='dark'] {--primary-color: var(--primary-color-dark);background-color: #333;color: #fff;
}.app {display: flex;flex-direction: column;align-items: center;justify-content: center;height: 100vh;
}#themeButton {padding: 10px 20px;background-color: var(--primary-color);color: #fff;border: none;cursor: pointer;transition: background-color 0.3s;
}#themeButton:hover {background-color: darken(var(--primary-color), 10%);
}.content {padding: 20px;border: 1px solid #ccc;border-radius: 5px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);text-align: center;
}
在模板中,通过绑定data-theme属性来控制主题变化。你可以使用条件语句来决定当前主题的值。
document.addEventListener('DOMContentLoaded', function () {const themeButton = document.getElementById('themeButton');const themeText = document.getElementById('themeText');let currentTheme = 'light';themeButton.addEventListener('click', function () {if (currentTheme === 'light') {document.documentElement.setAttribute('data-theme', 'dark');themeText.textContent = 'dark';currentTheme = 'dark';} else {document.documentElement.setAttribute('data-theme', 'light');themeText.textContent = 'light';currentTheme = 'light';}});
});