💡 목표
버튼을 누르면 각각 다른 컨텐츠가 보여지는 탭 메뉴 구현
📌 HTML
<div class="tab_menu">
<ul class="videoList">
<li class="is_on">
<div class="cont"></div>
</li>
<li>
<div class="cont"></div>
</li>
<li>
<div class="cont"></div>
</li>
<li>
<div class="cont"></div>
</li>
</ul>
<ul class="videoBtn">
<li class="is_on">
<button class="tabBtn" onclick="btnEvent()">1</button>
</li>
<li>
<button class="tabBtn" onclick="btnEvent()">2</button>
</li>
<li>
<button class="tabBtn" onclick="btnEvent()">3</button>
</li>
<li>
<button class="tabBtn" onclick="btnEvent()">4</button>
</li>
</ul>
</div>
📌 CSS
/* reset */
ul { list-style: none; }
button { border: none; }
/* 컨텐츠 */
.tab_menu { display: flex; flex-direction: column; align-items: center; justify-content: center; width: 90%; box-sizing: border-box; }
.tab_menu .videoList { width: 100%; margin-bottom: 10px;}
.tab_menu .videoList li .cont{ display: none; width: 100%; height: 100px; }
/* 컨텐츠 background color */
.tab_menu .videoList li:nth-child(1) .cont{ background-color: #ff8181; }
.tab_menu .videoList li:nth-child(2) .cont{ background-color: #fff281; }
.tab_menu .videoList li:nth-child(3) .cont{ background-color: #81d1ff; }
.tab_menu .videoList li:nth-child(4) .cont{ background-color: #ff81a7; }
/* is on */
.tab_menu .videoList li.is_on .cont{ display: block; }
/* 버튼 */
.tab_menu .videoBtn { display: flex; justify-content: space-between; gap: 10%; width: 100%; height: 100%; }
.tab_menu .videoBtn li { margin-top: 10px; flex-grow: 1; }
.tab_menu .videoBtn li .tabBtn{ width: 100%; padding: 20px; border-radius: 5px; background-color: #ddd; color: #fff; text-align: center; font-size: 18px; font-weight: 500; line-height: 22px;}
/* 버튼 background color */
.tab_menu .videoBtn li:nth-child(1).is_on .tabBtn{ background-color: #ff8181; }
.tab_menu .videoBtn li:nth-child(2).is_on .tabBtn{ background-color: #fff281; }
.tab_menu .videoBtn li:nth-child(3).is_on .tabBtn{ background-color: #81d1ff; }
.tab_menu .videoBtn li:nth-child(4).is_on .tabBtn{ background-color: #ff81a7; }
📌 JavaScript
function btnEvent() {
const tabMenu = document.querySelector('.tab_menu');
const tabList1 = Array.from(tabMenu.querySelectorAll('.videoList li'));
const tabList2 = Array.from(tabMenu.querySelectorAll('.videoBtn li'));
tabMenu.addEventListener('click', (e) => {
const target = e.target;
if (target.classList.contains('tabBtn')) {
e.preventDefault();
const index = tabList2.indexOf(target.parentNode);
if (index !== -1) {
tabList1.forEach((item, i) => {
item.classList.remove('is_on');
tabList2[i].classList.remove('is_on');
});
tabList1[index].classList.add('is_on');
tabList2[index].classList.add('is_on');
}
}
});
}
💛 결과물
💡 응용 - 카테고리 구현
728x90
반응형
'퍼블리싱 > Vanilla JS' 카테고리의 다른 글
[Vanilla JS] 스와이퍼 없이 슬라이더 구현하기 (+ play/stop/progress bar) (0) | 2024.05.28 |
---|---|
[Vanilla JS] 숫자 상승 애니메이션 / 카운트 애니메이션 (0) | 2023.10.27 |
[Vanilla JS] 스크롤 이벤트 구현 Scroll Event (1) | 2023.10.27 |
[Vanilla JS] 무한 슬라이더 구현 (0) | 2023.10.27 |
[Vanilla JS] 무한루프 슬라이더 구현 (1) | 2023.10.27 |