<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
.tab{
width: 600px;
height: 300px;
border:1px solid #000;
margin: 50px auto;
}
.tab ul, .tab ol{
list-style-type: none;
padding: 0;
margin: 0;
}
.tab ul{
height: 50px;
background-color: #eee;
display: flex;
justify-content: space-evenly;
align-items: center;
}
.tab ul li{
width: 100px;
height: 30px;
background-color: #abcdef;
text-align: center;
line-height: 30px;
}
.tab ul li.active{
background-color: #f00;
color: #fff;
}
.tab ol{
width: 600px;
height: 250px;
}
.tab ol li a img{
width: 600px;
height: 250px;
}
.tab ol li{
display:none;
}
.tab ol li.active{
display:block;
}
.tab{
cursor: pointer;
}
</style>
<body>
<div class="tab">
<ul>
<li class="active">向日葵</li>
<li>郁金香</li>
<li>红玫瑰</li>
</ul>
<ol>
<li class="active">
<a href="./images/1.jfif">
<img src="./images/1.jfif" alt="">
</a>
</li>
<li>
<a href="./images/2.webp">
<img src="./images/2.webp" alt="">
</a>
</li>
<li>
<a href="./images/3.jfif">
<img src="./images/3.jfif" alt="">
</a>
</li>
</ol>
</div>
</body>
<script>
class Tab{
constructor(classname){
// 添加属性
this.container = document.querySelector('.'+classname);
this.ulis = this.container.querySelectorAll('ul li')
this.olis = this.container.querySelectorAll('ol li')
}
// 定义方法 - 绑定事件
init(){
for(var i=0;i<this.ulis.length;i++){
this.ulis[i].onclick = this.click(i)
}
}
click(index){
return () => this.tab(index)
}
tab(index){
for(var i=0;i<this.ulis.length;i++){
this.ulis[i].className = ''
this.olis[i].className = ''
}
this.ulis[index].className = 'active'
this.olis[index].className = 'active'
}
}
var tab = new Tab('tab')
tab.init()
</script>
</html>
使用es6的class方法实现tab切换
最新推荐文章于 2023-04-11 21:15:41 发布