드롭다운 메뉴
Coddy HTML 여정의 JavaScript 실전 섹션에 포함된 레슨. 27개 중 15번째.
Dropdown 메뉴는 트리거되었을 때 추가 옵션을 표시하는 UI 구성 요소입니다. 너무 많은 공간을 차지하지 않으면서 content를 구성하기 위해 내비게이션에서 흔히 사용됩니다.
먼저 기본 드롭다운을 위한 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를 추가해 보겠습니다:
// Get the dropdown toggle button
const dropdownToggle = document.querySelector('.dropdown-toggle');
// Get the dropdown menu
const dropdownMenu = document.querySelector('.dropdown-menu');
// Add click event listener to the toggle button
dropdownToggle.addEventListener('click', function() {
// Toggle the 'show' class on the dropdown menu
dropdownMenu.classList.toggle('show');
});마지막으로 드롭다운 메뉴를 숨기거나 표시하도록 기본 CSS를 추가하세요:
.dropdown-menu {
display: none;
}
.dropdown-menu.show {
display: block;
}"Menu" button을 클릭하면 드롭다운 메뉴가 나타납니다. 다시 클릭하면 메뉴가 숨겨집니다.
챌린지
쉬움버튼을 클릭하면 표시되거나 숨겨지는 드롭다운 메뉴를 만드세요.
단계:
- HTML에서:
- 버튼에 클릭할 때
toggleDropdown이라는 함수를 호출하는onclick속성을 추가하세요
- 버튼에 클릭할 때
- JavaScript에서:
toggleDropdown이라는 함수를 만드세요- 함수 내부에서 ID가 “myDropdown”인 요소의 "show" class를 전환하세요
직접 해보기
<!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>
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
JavaScript 실전의 모든 레슨
직접 연습해 보세요: Web 플레이그라운드