要实现整个页面的深色主题切换,可以通过CSS变量和JavaScript来实现。以下是一个基本的实现步骤和示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Theme Switcher</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="theme-switcher">Switch to Dark Theme</button>
<div class="content">
<h1>Welcome to My Website</h1>
<p>This is a sample text.</p>
</div>
<script src="script.js"></script>
</body>
</html>
:root {
--background-color: #ffffff;
--text-color: #000000;
}
body.dark-theme {
--background-color: #121212;
--text-color: #ffffff;
}
body {
background-color: var(--background-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s;
}
.content {
padding: 20px;
}
document.getElementById('theme-switcher').addEventListener('click', function() {
document.body.classList.toggle('dark-theme');
this.textContent = document.body.classList.contains('dark-theme') ? 'Switch to Light Theme' : 'Switch to Dark Theme';
});
--background-color
和 --text-color
。.dark-theme
类来覆盖这些变量的值,实现深色主题。body
元素的dark-theme
类。通过这种方式,你可以轻松地在深色和浅色主题之间切换,提升用户体验并使网站更具个性化。
领取专属 10元无门槛券
手把手带您无忧上云