coding/web

javascript tab menu 탭메뉴 클래스만 붙여서 만들기

100a 2023. 12. 13. 22:38

 

탭메뉴

 

진짜 간단하게 작업했다.

클릭을 하는 탭메뉴와 그 탭에 관한 내용에

active라는 클래스를 붙이는 방식으로 만들었다.

 

 

 

html

<div class="section">
  <ul class="tabmenuBar">
    <li class="tabmenu tabmenu1 active">
      tabmenu1
    </li>
    <li class="tabmenu tabmenu2">
      tabmenu2
    </li>
    <li class="tabmenu tabmenu3">
      tabmenu3
    </li>
  </ul>
  <div class="contWrap">
    <div class="tabCont tabCont1 active">
      content1
    </div>
    <div class="tabCont tabCont2">
      content2
    </div>
    <div class="tabCont tabCont3">
      content3
    </div>
  </div><!-- contWrap -->
</div>

 

 

 

css

.section{
  margin:50px;
  width:500px;
  background:blue;
  padding:20px;
}

.tabmenuBar {
  display:flex;
  width:100%;
  align-items:center;
  padding:0;
  margin:0;
}
.tabmenuBar .tabmenu{
  list-style:none;
  padding:15px 20px;
  color:#fff;
  font-weight:600;
  cursor:pointer;
}
.tabmenu.active{
  background:#fff;
  color:blue;
}

.contWrap{
  padding:20px 0;
  background:#fff;
}
.contWrap .tabCont{
  display:none;
  padding:15px 20px;
  min-height:100px;
  font-size:20px;
}
.contWrap .tabCont.active{
  display:block;
}
.contWrap .tabCont.tabCont2{
  color:red;
  height:200px;
}
.contWrap .tabCont.tabCont3{
  color:green;
}

 

 

javascript

const tabmenus = document.querySelectorAll('.tabmenuBar .tabmenu');

tabmenus.forEach(function(els,index){
  els.addEventListener('click',function(){
    tabChange((index+1));
  });
});

function tabChange(num){
  document.querySelector('.tabmenu.active').classList.remove('active');
  document.querySelector('.tabmenu'+num).classList.add('active');
  document.querySelector('.tabCont.active').classList.remove('active');
  document.querySelector('.tabCont'+num).classList.add('active');
}