드롭다운 메뉴
Coddy HTML 여정의 JavaScript in Action 섹션에 포함된 레슨 — 27개 중 15번째.
드롭다운 메뉴는 트리거되었을 때 추가 옵션을 보여주는 UI 컴포넌트입니다. 공간을 너무 많이 차지하지 않으면서 콘텐츠를 정리하기 위해 탐색 메뉴에서 흔히 사용됩니다.
먼저, 기본적인 드롭다운을 위한 HTML 구조를 만들어 보겠습니다:
<div class="dropdown">
<button class="dropdown-toggle">Menu</button>
<div class="dropdown-menu">
<a href="#">Option 1</a>
<a href="#">Option 2</a>
<a href="#">Option 3</a>
</div>
</div>이제 드롭다운 표시 여부를 전환하는 JavaScript를 추가해 보겠습니다:
// 드롭다운 토글 버튼 가져오기
const dropdownToggle = document.querySelector('.dropdown-toggle');
// 드롭다운 메뉴 가져오기
const dropdownMenu = document.querySelector('.dropdown-menu');
// 토글 버튼에 클릭 이벤트 리스너 추가
dropdownToggle.addEventListener('click', function() {
// 드롭다운 메뉴에서 'show' 클래스 전환
dropdownMenu.classList.toggle('show');
});마지막으로, 드롭다운 메뉴를 숨기거나 표시하기 위한 기본적인 CSS를 추가합니다:
.dropdown-menu {
display: none;
}
.dropdown-menu.show {
display: block;
}"메뉴" 버튼을 클릭하면 드롭다운 메뉴가 나타납니다. 다시 클릭하면 메뉴가 숨겨집니다.
챌린지
쉬움버튼을 클릭했을 때 나타나거나 숨겨지는 드롭다운 메뉴를 만드세요.
단계:
- HTML에서:
- 버튼에 클릭 시
toggleDropdown이라는 이름의 함수를 호출하는onclick속성을 추가하세요.
- 버튼에 클릭 시
- JavaScript에서:
toggleDropdown이라는 함수를 생성하세요.- 함수 내부에서 ID가 “myDropdown”인 요소의 "show" 클래스를 토글하세요.
직접 해보기
<!DOCTYPE html>
<html>
<head>
<title>Save the Forests</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Save the Forests</h1>
<p>Even planting one or two trees makes a difference.</p>
</header>
<div class="dropdown">
<button class="dropbtn">Learn More ▼</button>
<div id="myDropdown" class="dropdown-content">
<a href="#">Why forests matter</a>
<a href="#">How to grow a tree</a>
<a href="#">Community projects</a>
</div>
</div>
<main>
<section>
<h2>Why Trees Are Important</h2>
<p>
Forests clean our air, give us oxygen, and are home to countless animals.
Each tree you plant helps fight climate change and supports life on Earth.
</p>
</section>
<section>
<h2> Start Small</h2>
<p>
Don’t wait for a big change. Start with just one or two trees in your yard or community.
Your small action inspires others!
</p>
</section>
</main>
<footer>
<p> Together we can make the planet greener.</p>
</footer>
<script src="script.js"></script>
</body>
</html>
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.