面向对象 重构版本
- 寻找一个“机器”,这个“机器”能够帮我们批量生产“选项卡”
- 目前来看并没有这个“机器”,那么我们就需要自己先创造一个“机器”
html
<div class="box1">
<ul class="header">
<li class="active">header_1</li>
<li>header_2</li>
<li>header_3</li>
</ul>
<ol class="content">
<li class="active">content_1</li>
<li>content_2</li>
<li>content_3</li>
</ol>
</div>
<div class="box2">
<ul class="header">
<li class="active">header_1</li>
<li>header_2</li>
<li>header_3</li>
</ul>
<ol class="content">
<li class="active">content_1</li>
<li>content_2</li>
<li>content_3</li>
</ol>
</div>
css
* {
margin: 0;
padding: 0;
}
ul,
ol {
list-style: none;
}
.header {
width: 600px;
height: 50px;
line-height: 50px;
text-align: center;
background-color: aqua;
display: flex;
}
.header li {
width: 200px;
}
.content {
width: 600px;
height: 400px;
line-height: 400px;
text-align: center;
font-size: 100px;
}
.content li {
display: none;
}
.header .active {
background-color: orange;
}
.content .active {
display: block;
background-color: yellow;
}
js
function Tabs(ele) {
this.ele = document.querySelector(ele)
this.hLi = [...this.ele.querySelectorAll('.header li')]
this.cLi = [...this.ele.querySelectorAll('.content li')]
this.init()
}
Tabs.prototype.init = function () {
let that = this
this.hLi.forEach(function (item, index) {
item.onclick = function () {
that.hLi.forEach(function (li, liIndex) {
li.classList.remove('active')
that.cLi[liIndex].classList.remove('active')
})
item.classList.add('active')
that.cLi[index].classList.add('active')
}
})
}
const t1 = new Tabs('.box1')
new Tabs('.box2')
面向过程版
js
var headerLi = [...document.querySelectorAll('.box1 .header li')]
var contentLi = [...document.querySelectorAll('.box1 .content li')]
headerLi.forEach(function (item, index) {
item.onclick = function () {
headerLi.forEach(function (li, liIndex) {
li.classList.remove('active')
contentLi[liIndex].classList.remove('active')
})
item.classList.add('active')
contentLi[index].classList.add('active')
}
})