折叠面板(展开/收起)
本课属于 Coddy HTML 学习旅程的“JavaScript 实战”单元。第 2 课,共 27 课。
手风琴是一种 UI 组件,可以展开和折叠内容区域。它常用于常见问题解答(点击问题 → 显示答案,再次点击 → 隐藏答案)。
原理很简单:点击标题时,JavaScript 会切换下方内容的显示状态。
要点:
- 我们有一个按钮和一个默认隐藏的内容元素(
display: none)。
- 点击按钮会触发函数,并传入应该打开的元素的 ID。
- 在函数内部:
- 如果元素已经显示(
display: block),我们就隐藏它(display: none)。 - 否则,我们就显示它(
display: block)。
- 如果元素已经显示(
<button onclick="toggle('p1')">Question 1</button>
<div id="p1" style="display:none;">Answer 1</div>
<script>
function toggle(id) {
const element = document.getElementById(id);
if (element.style.display === "block") {
element.style.display = "none";
} else {
element.style.display = "block";
}
}
</script>挑战
简单现在,我们的手风琴有三个问题。你的任务是添加第四个问题。
步骤:
- 创建一个新的
<button>,文本为:Should I add milk or drink it black? - 调用函数
onclick="togglePanel('q4')",将它连接到新的面板 - 创建一个
<div>,其id="q4",类为panel。 - 在 div 中写下答案:
It depends on your taste! Black coffee has stronger flavor, while milk softens the bitterness.
亲手试试
<!DOCTYPE html>
<html>
<head>
<title>FAQ Accordion</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>FAQ Coffee Lovers</h1>
<button class="accordion" onclick="togglePanel('q1')">What is the best way to brew coffee at home?</button>
<div id="q1" class="panel">
The French press and pour-over methods are popular for making rich, flavorful coffee at home.
</div>
<button class="accordion" onclick="togglePanel('q2')">Where do coffee beans come from?</button>
<div id="q2" class="panel">
Most coffee beans are grown in countries around the equator, such as Brazil, Ethiopia, and Colombia.
</div>
<button class="accordion" onclick="togglePanel('q3')">How late can I drink coffee?</button>
<div id="q3" class="panel">
It's best to avoid coffee 6 hours before bedtime, since caffeine can affect your sleep.
</div>
<script src="script.js"></script>
</body>
</html>这节课包含一个小测验。开始学习即可作答,并记录你的进度。
JavaScript 实战中的所有课
自己练习: Web 在线编辑器