<style>
* {
margin: 0;
padding: 0;
}
ul,ol,li {
list-style: none;
}
.tab {
width: 600px;
height: 400px;
border: 10px solid #333;
margin: 50px auto;
display: flex;
flex-direction: column;
}
ul {
height: 60px;
display: flex;
}
ul > li {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
font-size: 40px;
color: #fff;
background-color: skyblue;
cursor: pointer;
}
ul > li.active {
background-color: orange;
}
ol{
flex: 1;
position: relative;
}
ol >li {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
font-size: 100px;
color: #fff;
background-color: purple;
display: none;
justify-content: center;
align-items: center;
}
ol >li.active{
display: flex;
}
</style>
</head>
<body>
<div class="tab" id="box">
<ul>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ul>
<ol>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ol>
</div>
<script>
// 书写构造函数
function Tabs(ele) {
// 范围
this.ele = document.querySelector(ele);
// 在范围内找到所有可以点击的盒子
this.btns = this.ele.querySelectorAll("ul > li");
// 在范围内找到所有需要切换显示的盒子
this.tabs = this.ele.querySelectorAll("ol >li");
// 提前保存一下 this
var _this = this;
// 原型上书写方法
Tabs.prototype.change = function () {
// 执行给所有btns 里面的 按钮添加点击事件
for (var i = 0; i < this.btns.length; i++) {
// 提前保存索引
this.btns[i].setAttribute("index",i);
this.btns[i].addEventListener("click",function(){
// 自己只有勇于没有,就会去上一级作用域查找
for (var j = 0; j < _this.btns.length; j++) {
_this.btns[j].className = " ";
_this.tabs[j].className = " ";
}
// 当前点击的这个li 有active 类名
this.className = "active";
// 拿到当前 li身上保存的索引
var index = this.getAttribute("index") - 0;
_this.tabs[index].className = "active";
})
}
}
}
// 选项卡使用的时候就可以了
var t = new Tabs("#box");
// 实例对象在调用方法
t.change();
</script>
</body>