<!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>
<style>
.tab1{
width: 300px;
height: 200px;
border:1px solid #000;
margin: 50px auto;
}
.tab1 ul, .tab1 ol{
list-style-type: none;
padding: 0;
margin: 0;
}
.tab1 ul{
height: 50px;
background-color: #eee;
display: flex;
justify-content: space-evenly;
align-items: center;
}
.tab1 ul li{
width: 100px;
height: 30px;
background-color: #abcdef;
text-align: center;
line-height: 30px;
}
.tab1 ul li.active{
background-color: #f00;
color: #fff;
}
.tab1 ol{
width: 300px;
height: 150px;
}
.tab1 ol li a img{
width: 300px;
height: 150px;
}
.tab1 ol li{
display:none;
}
.tab1 ol li.active{
display:block;
}
.tab1{
cursor: pointer;
}
</style>
<div class="tab1">
<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>
// 创建对象 - 自定义构造函数
function Tab(cname){
// 使用css选择器选择标签元素的时候,不一定方法非用document来调用
// 标签元素.querySelector()
// 标签元素.querySelectorAll()
// 在指定的标签元素内部通过css选择器来获取标签
// 添加属性 - 在构造函数中
this.container = document.querySelector('.'+cname);
this.ulis = this.container.querySelectorAll('ul li');
this.olis = this.container.querySelectorAll('ol li');
}
Tab.prototype.init = function(){
for(let i=0;i<this.ulis.length;i++){ // 这里的this是t
// 这里的this是t
this.ulis[i].onclick = () => {
for(var j=0;j<this.ulis.length;j++){
this.ulis[j].className = ''
this.olis[j].className = ''
}
this.ulis[i].className = 'active'
// 这里的this是t
this.olis[i].className = 'active'
}
}
}
var t = new Tab('tab')
t.init()
var t1 = new Tab('tab1')
t1.init()
</script>
</html>
面向对象写tab切换(四)
最新推荐文章于 2022-10-20 22:24:00 发布