一月 19, 2017 · ES6 使用ES6的面向对象语法实现选项卡 基本的选项卡css部分1234567891011121314button.active { background-color: orange;}div { width: 100px; height: 100px; background-color: #999; display: none;}div.on { display: block;} html部分12345678<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> js1234567891011121314151617181920212223242526 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'); 使用继承给选项卡添加自动轮播功能js123456789101112131415161718class 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');