탭
Coddy HTML 여정의 JavaScript 실전 섹션에 포함된 레슨. 27개 중 1번째.
탭을 사용하면 페이지를 벗어나지 않고도 서로 다른 콘텐츠 간에 전환할 수 있습니다. 섹션 4에서는 HTML과 CSS를 사용해 탭을 만들었습니다. 이제 JavaScript를 사용해 보겠습니다.
핵심 사항:
- display 속성(
none/block)을 사용하여 요소를 숨기고 표시합니다. - 사용자가 탭을 클릭하면 함수를 호출하고 탭의 ID를 전달합니다.
- 함수 내부에서
querySelectorAll+forEach를 사용해 모든 탭 콘텐츠를 숨깁니다. - 마지막으로, ID와 일치하는 항목을 표시합니다.
<div class="tabs">
<button class="tab" onclick="openTab('services')">Services</button>
<button class="tab" onclick="openTab('contact')">Contact</button>
</div>
<div id="services" class="tab-content">Our services are listed here.</div>
<div id="contact" class="tab-content" style="display:none;">Contact us at contact@example.com.</div>
<script>
function openTab(tabId) {
// Hide all tab contents
document.querySelectorAll('.tab-content').forEach(el => el.style.display = 'none');
// Show the selected tab
document.getElementById(tabId).style.display = 'block';
}
</script>챌린지
쉬움탭이 작동하도록 하는 JavaScript 함수는 이미 작성했습니다. 할 일:
- 각 탭 버튼에
onclick속성을 추가하여 탭을 클릭하면 해당 콘텐츠가 표시되도록 합니다. - 함수
openTab()을 호출합니다. - 탭 콘텐츠의 id(
home,about또는contact)를 전달합니다.
직접 해보기
<!DOCTYPE html>
<html>
<head>
<title>Simple Tabs Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="tabs">
<!-- 각 버튼은 함수를 호출하고 탭의 ID를 전달합니다 -->
<button class="tab" >Home</button>
<button class="tab" >About</button>
<button class="tab" >Contact</button>
</div>
<!-- 기본적으로 "Home"만 표시됩니다 -->
<div id="home" class="tab-content">Welcome to the homepage!</div>
<div id="about" class="tab-content" style="display:none;">Learn more about us here.</div>
<div id="contact" class="tab-content" style="display:none;">Get in touch with us.</div>
<script src="script.js"></script>
</body>
</html>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
JavaScript 실전의 모든 레슨
직접 연습해 보세요: Web 플레이그라운드