深色和浅色主题
本课属于 Coddy HTML 学习旅程的“JavaScript 实战”单元。第 16 课,共 27 课。
实现深色/浅色主题切换是现代网站中的常见功能。让我们学习如何使用 JavaScript 创建一个简单的主题切换器。
首先,创建一个可以在不同主题之间切换的按钮:
<button id="themeToggle">Theme Toggle</button>接下来,为浅色主题和深色主题添加一些基础 CSS:
<style>
:root {
--background-color: #ffffff;
--text-color: #333333;
}
body {
background-color: var(--background-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s;
}
.dark-theme {
--background-color: #222222;
--text-color: #f5f5f5;
}
</style>现在,我们来添加 JavaScript,以便在不同主题之间切换:
const themeToggle = document.getElementById('themeToggle');
themeToggle.addEventListener('click', function() {
document.body.classList.toggle('dark-theme');
});点击按钮时,它会切换 body 元素上的“dark-theme”类。
挑战
简单在按钮的点击事件监听器中,添加代码,以切换 body 元素上的 "dark-mode" 类。
亲手试试
<!DOCTYPE html>
<html>
<head>
<title>Dark/light themes</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Hygge ✨</h1>
<button id="themeToggle" class="toggle-btn">Toggle Theme</button>
</header>
<main>
<section class="intro">
<img src="https://images.unsplash.com/photo-1519710164239-da123dc03ef4?auto=format&fit=crop&w=1350&q=80" alt="Cozy hygge scene" class="hero-img">
<p>
<strong>Hygge</strong> is a Danish concept that embodies coziness, comfort, and a sense of well-being.
It’s about enjoying life’s simple pleasures — candles, warm drinks, good company, and soft blankets.
</p>
</section>
<section class="philosophy">
<h2>The Philosophy</h2>
<p>
Hygge is less about things and more about atmosphere and feelings.
It’s creating moments of calm, warmth, and togetherness — a way to nurture happiness in everyday life.
</p>
</section>
<section class="origin">
<h2>Where It Comes From</h2>
<p>
Originating from Denmark, hygge reflects the Danish culture’s deep appreciation for balance, comfort,
and community. It’s often credited as one of the reasons why Denmark consistently ranks among the
happiest countries in the world.
</p>
</section>
</main>
<footer>
<p>☕ Embrace hygge in your daily life.</p>
</footer>
<script src="script.js"></script>
</body>
</html>
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
JavaScript 实战中的所有课
自己练习: Web 在线编辑器