잡다한 팁
HTML에서 탭으로 페이지 변경하기
choco2706
2024. 5. 3. 20:45
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#merong {
position: relative;
width:300px;
height:300px;
}
.tab {
/* position을 absolute로 주고 모든 .tab들을 한곳에 모아둔다. */
position: absolute;
/* 크기, 위치 고정 */
width:300px;
height:300px;
left:0px;
top:0px;
}
/* 구분하기 위한 각 id값에 background-color 설정 */
#tab1 {
background-color: lightblue;
}
#tab2 {
background-color: yellowgreen;
}
#tab3 {
background-color: rgb(253, 107, 107);
}
</style>
</head>
<body>
<button onclick="showTab(0)">탭1</button>
<button onclick="showTab(1)">탭2</button>
<button onclick="showTab(2)">탭3</button>
<br>
<br>
<div id="merong">
<div id="tab1" class="tab">
<h1>탭1</h1>
</div>
<div id="tab2" class="tab">
<h1>탭2</h1>
</div>
<div id="tab3" class="tab">
<h1>탭3</h1>
</div>
</div>
<script>
const tabs = document.querySelectorAll(".tab");
function tabInit(){
for(let i=0; i<tabs.length; i++){
// 모든 div의 z-index 값을 1로 수정
tabs[i].style.zIndex =1;
}
}
function showTab(num){
tabInit();//초기화
// z-index의 값이 클수록 먼저 보여진다.
// tabs[num]의 z-index 값을 100으로 수정
tabs[num].style.zIndex = 100;
}
</script>
</body>
</html>
탭1
탭2
탭3