原生js实现选项卡效果

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width; initial-scale=1.0; minimum-scale=1.0; maximum-scale=2.0" />
<title>选项卡-叶子制作</title>
<meta name="description" content="js选项卡" />
<meta name="keywords" content="叶子" />
<style type="text/css">
*{padding:0; margin:0; border:none;list-style: none;}
body{width:800px;margin:50px auto;}
.tab{width:800px;color:#fff;text-align: center;}
.tab .tit{overflow:hidden;}
.tab .tit li{display: inline-block;float:left;margin-right:10px;width:100px;height:30px;line-height:30px;background:blue;}
.tab .tit li.on{background:red;}
.tab>div{display: none;width:800px;height:300px;line-height:300px;background:red;font-size:80px;font-weight: bold;}
.tab>div.on{display:block;}
</style>
</head>
<body>
<div id="tab1" class="tab">
<ul class="tit">
<li>111</li>
<li>222</li>
<li>333</li>
</ul>
<div>111</div>
<div>222</div>
<div>333</div>
</div>
<div id="tab2" class="tab">
<ul class="tit">
<li>111</li>
<li>222</li>
<li>333</li>
</ul>
<div>111</div>
<div>222</div>
<div>333</div>
</div>
<script type="text/javascript">
function tab(tabId){
var tab = document.getElementById(tabId);
var oLis = tab.getElementsByTagName("li");
var oDiv = tab.getElementsByTagName("div");

oLis.item(0).className = "on"; //给li[0]添加类名;
oDiv.item(0).className = "on"; //给div[0]添加类名;

for(var i=0;i<oLis.length;i++){
oLis.item(i).wkxIndex = i; //自定义属性;
oLis.item(i).onclick = function(){ //点击li时;
for(var i=0;i<oLis.length;i++){ //利用循环在点击li时将li和div上所有的on类名设置为空;
oLis.item(i).className = null;
oDiv.item(i).className = null;
}
oLis.item(this.wkxIndex).className = "on"; //利用自定义属性将当前点击的给定类名on(添加样式);
oDiv.item(this.wkxIndex).className = "on";
}
}
}
tab("tab1"); //传递使用选项卡的div的id值;
tab("tab2");
</script>
</body>
</html>

posted on 2015-04-01 11:33  树袋熊的叶子  阅读(198)  评论(0编辑  收藏  举报

导航