🐶 etc/2022기록
[20230629]tab js
서카츄
2023. 6. 29. 16:19
/*
탭메뉴를 클릭하면 관련 내용이 나타나고
하이라이트 배경이 활성화된 메뉴위치로 이동합니다.
*/
// javascript 사용버전
const tabMenu = document.querySelectorAll('.tab-menu li');
const tabContent = document.querySelectorAll('#tab-content > div');
const highLight = document.querySelector('.highlight');
//클래스명 추가&삭제
/*
클래스명 제어
대상.classList.add('클래스명');
대상.classList.remove('클래스명');
*/
/*
요소의 위치를 찾아내는 법
대상.offsetLeft -> 가까운 부모중에 position 기본값이 아닌요소를 기준으로 왼쪽에서 떨어진 값
요소의너비
대상.offsetWidth 보더까지 크기를 반환해준다.
*/
function showContent(num){
//forEach tabContent가 모두 display:none;으로 변경
// tabContent.forEach(function(item){
// item.style.display='none';
// });
// //num의 숫자에 맞는 tabContent 보이도록
// tabContent[num].style.display = 'block';
//모든메뉴에서 active 클래스명 제거, 인덱스번호에 해당하는 그 요소에만 active 추가
// for(let j=0; j<tabMenu.length; j++){
// tabMenu[j].classList.remove('active');
// }
// tabMenu[num].classList.add('active');
tabContent.forEach(function(item){
item.classList.remove('active');
});
tabContent[num].classList.add('active');
}
showContent(1);
//메뉴를 클릭하면, 3개의 메뉴중 몇번째 클릭헀는지 숫자 -> showContent
// tabMenu[0].addEventListener('click',function(){
// alert('메뉴가 클릭됨');
// });
// for(let i = 0; i<tabMenu.length; i++){
// tabMenu[i].addEventListener('click',function(){
// showContent(i);
// });
// }
tabMenu.forEach(function(item,index){
item.addEventListener('click',function(e){
e.preventDefault();
showContent(index);
console.log(this.offsetLeft, this.offsetWidth);
//highLight의너비, highLight의 left
highLight.style.left = `${this.offsetLeft}px`;
highLight.style.width = `${this.offsetWidth}px`;
});
});
//css 사용버전