原理:还是排他功能。这个tab栏我用了两个排他功能来实现的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
div{
margin: 100px 100px;
}
li{
list-style-type: none;
}
#top{
width: 500px;
height: 40px;
line-height: 40px;
text-align: center;
background: #f2f2f2;
}
#top li{
width: 100px;
float: left;
}
#top li.current{
background: lightcoral;
}
#bottom{
width: 500px;
height: 140px;
background: lightcoral;
position: relative;
}
#bottom li{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
padding-left: 15px;
box-sizing: border-box;
display: none;
}
#bottom li.current{
display: block;
}
</style>
</head>
<body>
<div>
<ul id="top">
<li class="current">周一</li>
<li>周二</li>
<li>周三</li>
<li>周四</li>
<li>周五</li>
</ul>
<ul id="bottom">
<li class="current">我是周一</li>
<li>我是周二</li>
<li>我是周三</li>
<li>我是周四</li>
<li>我是周五</li>
</ul>
</div>
<script>
var navList=document.getElementById('top').getElementsByTagName('li');
var contents=document.getElementById('bottom').getElementsByTagName('li');
for(var i=0;i<navList.length;i++){
//在事件之前我先把索引给准备好
navList[i].setAttribute("index",i);
navList[i].onclick=function(){
for(var j=0;j<navList.length;j++){
//removeAttribute既可以移除自定义属性,也可以移除非自定义属性
navList[j].removeAttribute('class');
}
this.className="current";
//将索引值先给存下来
var num=this.getAttribute("index");
for(var k=0;k<contents.length;k++){
contents[k].removeAttribute('class');
}
contents[num].className="current";
}
}
</script>
</body>
</html>
排他功能原理不清楚的小伙伴请戳:原生js实现按钮的排他功能???