一、案例分析
- 选项卡的
面向对象
是对选项卡面向过程
的优化,当我们需要时直接调用
即可
![在这里插入图片描述](https://img-blog.csdnimg.cn/786eb544232c4becace6593d04f5c760.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/5481f7ac07b549fdb40d0e1c41847c41.png)
二、HTML和CSS代码
<div id="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 id="box2">
<ul class="header">
<li class="active">header_1</li>
<li>header_2</li>
<li>header_3</li>
<li>header_4</li>
</ul>
<ol class="content">
<li class="active">content_1</li>
<li>content_2</li>
<li>content_3</li>
<li>content_4</li>
</ol>
</div>
<style>
* {
padding: 0;
margin: 0;
}
ul,
ol {
list-style: none;
}
.header {
width: 600px;
height: 50px;
line-height: 50px;
text-align: center;
background-color: pink;
display: flex;
}
.header li {
width: 200px;
}
.content {
width: 600px;
height: 400px;
line-height: 400px;
text-align: center;
}
.header .active {
background-color: aquamarine;
}
.content li {
display: none;
font-size: 50px;
}
.content .active {
display: block;
background-color: orange;
}
</style>
三、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')
const t2 = new Tabs('#box2')
四、封装
1、ES5 构造函数
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");
};
});
};
2、ES6 CLASS
class Tabs {
constructor(ele) {
this.ele = document.querySelector(ele);
this.hLi = [...this.ele.querySelectorAll(".header li")];
this.cLi = [...this.ele.querySelectorAll(".content li")];
this.init();
}
init() {
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");
};
});
}
}
3、调用
<script src="./Tabs.js"></script>
<script>
const t1 = new Tabs('#box1')
const t2 = new Tabs('#box2')
</script>