<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
ol,ul li{
list-style: none;
}
.box{
width: 500px;
height: 500px;
border: 1px solid black;
margin: 0 auto;
}
ol{
width: 100%;
height: 100px;
background-color:orangered;
display: flex;
justify-content: space-around;
}
ol li{
text-align: center;
line-height: 100px;
flex: 1;
cursor: pointer;
}
ul{
width: 100%;
height: 400px;
/* background-color: chartreuse; */
}
ul li{
width: 100%;
height: 400px;
background-color: orange;
font-size: 100px;
text-align: center;
line-height: 400px;
display: none;
}
ol li.active{
background-color: brown;
display: block;
}
ul li.active{
background-color:skyblue;
display: block;
}
</style>
</head>
<body>
<div class="box" id="pox1">
<ol>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ol>
<ul>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<div class="box" id="pox2">
<ol>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ol>
<ul>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
</body>
<script>
//第一种写法 用let 和 forEach 还有箭头函数 循环遍历 不用考虑过多的this指向问题 都是this指向实力对象
// 创建一个构造函数
function Fn(select,type='click'){
this.box = document.querySelector(select) ;
this.btn_top = this.box.querySelectorAll('ol>li');
this.btn = this.box.querySelectorAll('ul>li');
this.type = type ;
this.tab() ;
}
Fn.prototype.tab = function(){
//遍历 btn_top
this.btn_top.forEach((item,index) => {
item.addEventListener(this.type,() => {
for( let i = 0 ; i < this.btn_top.length ; i ++){
this.btn_top[i].classList.remove('active') ;
this.btn[i].classList.remove('active') ;
}
//添加类名
this.btn_top[index].classList.add('active') ;
this.btn[index].classList.add('active') ;
})
})
}
new Fn('#pox1','click') ;
new Fn('#pox2','mouseover') ;
//第二种写法 用 for 循环 和 var 定义变量 主要考虑this的指向问题
// 创建一个构造函数
function Fn(select){
// 给实力对象添加元素 (获取元素)
this.box = document.querySelector(select)
this.ol_btn = this.box.querySelectorAll('ol li') ;
this.ul_btn = this.box.querySelectorAll('ul li') ;
}
Fn.prototype.Move = function(){
//创建一些方法
// 把this指向存在一个变量里
const instance = this ;
for( var i = 0 ; i < this.ol_btn.length ; i ++){
// 添加一个自定义属性
this.ol_btn[i].dataset.i = i ;
this.ol_btn[i].addEventListener('click' , function(){
// this 是你点击的这个 li
// 拿到这个 li 身上记录的自定义属性 data-i 的值,
const index = this.dataset.i - 0
for( var i = 0 ; i < instance.ol_btn.length ; i ++ ){
instance.ol_btn[i].classList.remove('active') ;
instance.ul_btn[i].classList.remove('active') ;
}
instance.ol_btn[index].classList.add('active') ;
instance.ul_btn[index].classList.add('active') ;
})
}
}
const p = new Fn('.box') ;
p.Move() ;
</script>
</html>