这里使用原生JS实现简易的选项卡,下一篇用JQuery实现简易的选型卡,大家可以感觉哪个更好用。
HTML代码如下:
<div class="box">
<ul><li class="active">新闻</li><li>招聘</li><li>广告</li></ul>
<div class="cont">
<div class="cont1">第一个选项卡的内容区域,111111</div>
<div class="cont2">第二个选项卡的内容区域,222222222</div>
<div class="cont3">第三个选项卡的内容区域,333333</div>
</div>
</div>
CSS样式代码如下:
.box{width: 500px;height: 400px;border: solid 1px black;margin: 20px auto;}
.box ul{margin: 0;padding: 0;list-style: none;height: 40px;line-height:40px;display: flex;background: #ccc;text-align:enter}
.box li{flex:1;border-left: solid 1px black;border-right: solid 1px black;text-align: center}
.box li.active{background: red;}
.cont div{width: 500px;height: 360px;display: none;}
.cont .cont1{background: #f0f;display: block;}
.cont .cont2{background: #f00;}
.cont .cont3{background: #00f;}
JavaScript代码如下:
function Tab(){
this.li = document.querySelectorAll(".box li");
this.cont = document.querySelectorAll(".cont div");
this.addEvent();
}
Tab.prototype.addEvent = function(){
var that = this;
for(let i=0;i<this.li.length;i++){
this.li[i].onclick = function(){
that.setActive(i);
}
}
}
Tab.prototype.setActive = function(iNow){
for(var i=0;i<this.li.length;i++){
this.li[i].className = "";
this.cont[i].style.display = "none";
}
this.li[iNow].className = "active";
this.cont[iNow].style.display = "block";
}
new Tab();