用面向对象的方式实现的简单tab切换功能 代码可以复用,第二个实现了简单的自动切换加了个定时器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>ES6-tab</title>
<link rel="stylesheet" href="">
<style>
.on {background: #f60;color:#fff;}
.box div{display: none;
border: 1px solid #000;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="box" id="box">
<input type="button" class="on" value="aaa">
<input type="button" value="bbb">
<input type="button" value="ccc">
<div style="display: block">111</div>
<div>222</div>
<div>333</div>
</div>
<div class="box" id="box2">
<input type="button" class="on" value="aaa">
<input type="button" value="bbb">
<input type="button" value="ccc">
<div style="display: block">111</div>
<div>222</div>
<div>333</div>
</div>
<script>
class Tab{
constructor(id){
this.oBox = document.getElementById(id);
this.aBtn = this.oBox.getElementsByTagName("input");
this.aDiv = this.oBox.getElementsByTagName("div");
this.init();
this.iNo = 0;
}
init(){
for(let i=0;i<this.aBtn.length;i++){
this.aBtn[i].οnclick=function(){
this.hide();
this.show(i);
}.bind(this)
}
}
hide(){
for (let i = 0; i < this.aBtn.length; i++) {
this.aBtn[i].className="";
this.aDiv[i].style.display="none";
}
}
show(index){
this.aBtn[index].className="on";
this.aDiv[index].style.display="block"
}
};
window.οnlοad=function(){
new Tab('box');
new AutoTab('box2');
}
class AutoTab extends Tab{
constructor(id){
super(id);
setInterval(this.next.bind(this),1000)
}
next(){
this.iNo++;
console.log("123")
if(this.iNo == this.aBtn.length){
this.iNo = 0;
}
this.hide();
this.show(this.iNo)
}
}
</script>
</body>
</html>