基本的选项卡

css部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
button.active {
background-color: orange;
}

div {
width: 100px;
height: 100px;
background-color: #999;
display: none;
}

div.on {
display: block;
}
html部分
1
2
3
4
5
6
7
8
<span id="tab1">
<button class="active">111</button>
<button>222</button>
<button>333</button>
<div class="on">111</div>
<div>222</div>
<div>333</div>
</span>
js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 class tab {
constructor(id) {
var x = document.getElementById(id);
this.btn = x.getElementsByTagName('button');
this.div = x.getElementsByTagName('div');
this.show();
}

hide() {
for (let i = 0; i < this.btn.length; i++) {
this.btn[i].className = '';
this.div[i].className = '';
}
}

show() {
for (let i = 0; i < this.btn.length; i++) {
this.btn[i].onclick = function () {
this.hide();
this.btn[i].className = 'active';
this.div[i].className = 'on';
}.bind(this);
}
}
}
new tab('tab1');

使用继承给选项卡添加自动轮播功能

js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class tabAuto extends tab {
constructor(id) {
super(id);
this.index = 0;
setInterval(this.next.bind(this), 500);
}
next() {
this.index++;
this.index=this.index == this.btn.length ? 0 : this.index;
for (let i = 0; i < this.btn.length; i++) {
this.hide();
this.btn[this.index].className = 'active';
this.div[this.index].className = 'on';
}
}
}

var tab2 = new tabAuto('tab2');