javascript - tab menu

erica·2023년 1월 10일
0
<article>
    <h2> Tab Sample</h2>
    <div class="tab-head">
    	<a href="#" class="active">HTML</a>
        <a href="#">CSS</a>
        <a href="#">JAVASCRIPT</a>
    </div>
    <div class="tab-body">
        <div class="active">HTML 소개 공간입니다.</div>
        <div>CSS 소개 공간입니다.</div>
        <div>JAVASCRIPT 소개 공간입니다.</div>
    </div>

<style>
article {width: 60%; margin: 100px auto;}
.tab-head a {display: inline-block; background: #999; color: #fff; padding: 15px 40px; text-decoration: none;}
.tab-head a.active {background: coral;}

.tab-body {position: relative;}
.tab-body div {background: #eee; width: 100%; height: 400px; position: absolute; left: 0; top: 0; display: none; justify-content: center; align-items: center;}
.tab-body div.active {display: flex;}
</style>
<script>
const tabMenu = document.querySelectorAll('.tab-head a');
const tabContents = document.querySelectorAll('.tab-body div');
 
let idx = 0;
tabMenu.forEach((btn, key)=>{
	btn.onclick = function(){
    	tabMenu[idx].classList.remove('active');
        tabMenu[key].classList.add('active');
 
 		tabContents[idx].classList.remove('active');
        tabContents[key].classList.add('active');
        idx = key;  
    }
})
</script>

</article>

forEach 문을 활용한 탭메뉴 예시

idx를 통해 클래스 삭제 / key 값을 통해 클래스 추가

profile
응미씨

0개의 댓글