아코디언 (펼치기/접기)
Coddy HTML 여정의 JavaScript in Action 섹션에 포함된 레슨 — 27개 중 2번째.
아코디언은 콘텐츠 섹션을 확장하거나 축소할 수 있는 UI 컴포넌트입니다. 자주 묻는 질문(FAQ)에 자주 사용됩니다(질문 클릭 → 답변 표시, 다시 클릭 → 숨김).
원리는 간단합니다. 헤더를 클릭하면 JavaScript가 그 아래에 있는 콘텐츠의 가시성을 토글(전환)합니다.
주요 사항:
- 버튼과 기본적으로 숨겨져 있는(
display: none) 콘텐츠 요소가 있습니다.
- 버튼을 클릭하면 함수가 실행되고 열려야 하는 요소의 ID를 전달합니다.
- 함수 내부에서:
- 요소가 이미 표시되고 있는 경우 (
display: block), 우리는 그것을 숨깁니다 (display: none). - 그렇지 않으면, 우리는 그것을 표시합니다 (
display: block).
- 요소가 이미 표시되고 있는 경우 (
<button onclick="toggle('p1')">질문 1</button>
<div id="p1" style="display:none;">답변 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')"함수를 호출하여 새로운 패널에 연결하세요.id="q4"와panel클래스를 가진<div>를 생성하세요.- 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>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.