탭
Coddy HTML 여정의 JavaScript in Action 섹션에 포함된 레슨 — 27개 중 1번째.
탭을 사용하면 사용자가 페이지를 벗어나지 않고도 서로 다른 콘텐츠 사이를 전환할 수 있습니다. 섹션 4에서는 HTML과 CSS를 사용하여 탭을 만들었습니다. 이제 JavaScript를 사용해 보겠습니다.
주요 사항:
- 우리는 display 속성(
none/block)을 사용하여 요소를 숨기거나 표시합니다. - 사용자가 탭을 클릭하면, 함수를 호출하고 탭의 ID를 전달합니다.
- 함수 내부에서, 모든 탭 콘텐츠를 숨기기 위해
<strong>querySelectorAll</strong>+<strong>forEach</strong>를 사용합니다. - 마지막으로, ID와 일치하는 항목을 표시합니다.
<div class="tabs">
<button class="tab" onclick="openTab('services')">서비스</button>
<button class="tab" onclick="openTab('contact')">연락처</button>
</div>
<div id="services" class="tab-content">저희 서비스 목록이 여기에 표시됩니다.</div>
<div id="contact" class="tab-content" style="display:none;">contact@example.com으로 문의해 주세요.</div>
<script>
function openTab(tabId) {
// 모든 탭 콘텐츠 숨기기
document.querySelectorAll('.tab-content').forEach(el => el.style.display = 'none');
// 선택된 탭 표시하기
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">
<!-- Each button calls the function and passes the tab's ID -->
<button class="tab" >Home</button>
<button class="tab" >About</button>
<button class="tab" >Contact</button>
</div>
<!-- By default, only "Home" is visible -->
<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>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.