본문 바로가기

자바스크립트

탭연습

자바스크립트 탭 연습

마크업

<div id="tab_wrap">

<ul id="tab">

<li><a href="#tab_cont1" class="on">Tab1</a></li>

<li><a href="#tab_cont2">Tab2</a></li>

<li><a href="#tab_cont3">Tab3</a></li>

<li><a href="#tab_cont4">Tab4</a></li>

<li><a href="#tab_cont5">Tab5</a></li>

</ul>

<div id="tab_cont1" class="tab_cont">Cont1</div>

<div id="tab_cont2" class="tab_cont" style="display:none">Cont2</div>

<div id="tab_cont3" class="tab_cont" style="display:none">Cont3</div>

<div id="tab_cont4" class="tab_cont" style="display:none">Cont4</div>

<div id="tab_cont5" class="tab_cont" style="display:none">Cont5</div>

</div>


자바스크립트

<script type="text/javascript">

// Tab

var tabFun = function(tabAreaId){

var tab_wrap = document.getElementById(tabAreaId),

tabNav = tab_wrap.getElementsByTagName("ul")[0],

tabLink = tabNav.getElementsByTagName("a"),

linkArr = [];


for(var i=0; i<tabLink.length; i++){

var link_href = tabLink[i].getAttribute("href").split("#")[1];

linkArr.push(link_href);


tabLink[i].onclick = function(){

var href_value = this.hash.split("#")[1];

for(var j=0; j<linkArr.length; j++){

tabLink[j].className = '';

document.getElementById(linkArr[j]).style.display = "none";

if(href_value == linkArr[j]){

this.className = 'on';

document.getElementById(href_value).style.display = "block";

}

}

return false;

}

}

}

tabFun('tab_wrap');

</script>


TEST

Cont1