若要是直接在数组遍历时输出,不论点击哪个,则都出i的最大值,即数组的长度。所以 将索引放在属性里面;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>tab栏封装</title>
<style>
body,ul{
padding: 0;
margin: 0;
}
ul{
list-style: none;
}
.tab{
width: 300px;
border: 1px solid #ccc;
margin:100px auto;
}
.tab .header{
overflow: hidden;
}
.tab span{
float: left;
display: inline-block;
width: 70px;
height: 40px;
line-height: 40px;
padding-right:5px;
text-align: center;
border-bottom: 1px solid #ccc;
}
.tab span.current{
background: #eee;
}
.tab ul{
height: 200px;
}
.tab ul li{
height: 200px;
background: #eee;
display: none;
}
.tab ul li.current{
display: block;
}
</style>
<script>
window.onload = function(){
function $(id){ return document.getElementById(id);}
function tab(obj){
var spans = $(obj).getElementsByTagName('span');
var lis = $(obj).getElementsByTagName('li');
for(var i = 0; i< spans.length; i++){
spans[i].index=i; //自定义属性,将索引放在数组的属性里面
spans[i].onmouseover = function(){
for(var j = 0; j< lis.length; j++){//排他思想
lis[j].className ="";
spans[j].className="";
}
this.className="current";
lis[this.index].className="current";
}
}
}
tab("clothes"); //将tab封装成函数,防止互相影响
tab("beautity");
}
</script>
</head>
<body>
<div id="clothes" class="tab">
<div class="header">
<span class="current">新闻</span>
<span>杭州</span>
<span>浙江</span>
<span>娱乐</span>
</div>
<div>
<ul>
<li class="current">新闻模块</li>
<li>杭州模块</li>
<li>浙江模块</li>
<li>娱乐模块</li>
</ul>
</div>
</div>
<div id="beautity" class="tab">
<div class="header">
<span class="current">新闻</span>
<span>杭州</span>
<span>浙江</span>
<span>娱乐</span>
</div>
<div>
<ul>
<li class="current">新闻模块</li>
<li>杭州模块</li>
<li>浙江模块</li>
<li>娱乐模块</li>
</ul>
</div>
</div>
</body>
</html>