<!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>
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
li{
list-style: none;
}
.box{
display: flex;
height: 100vh;
overflow: hidden;
}
.box-l{
width: 80px;
}
.box-l li{
height: 80px;
line-height: 80px;
padding-left: 20px;
border: 1px solid rgb(228, 228, 228);
}
.box-r{
margin-left: 20px;
width: 300px;
overflow: auto;
}
.active{
background-color: purple;
}
</style>
</head>
<body>
<div class="box">
<div class="box-l">
<ul>
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<div class="box-r">
<ul>
<li style="height: 500px;background-color: green;">1</li>
<li style="height: 300px;background-color: yellow;">2</li>
<li style="height: 200px;background-color: red;">3</li>
<li style="height: 400px;background-color: blue;">4</li>
<li style="height: 1000px;background-color: #fff;"></li>
</ul>
</div>
</div>
</body>
<script>
const rbox=document.querySelector('.box-r');
const lbox=document.querySelector('.box-l');
const lLi=lbox.querySelectorAll('li');
const rLi=rbox.querySelectorAll('li');
let currentIndex=0;
function getH(){
let arr=[];
let h=0;
arr.push(0);
rLi.forEach(li=>{
h+=li.clientHeight;
arr.push(h)
})
arr.pop();//删掉最后一个凑数的
return arr;
}
const arrH=getH();
//右侧滚动,左侧选中
rbox.addEventListener('scroll',function(){
for(let i=1;i<arrH.length;i++){
if(this.scrollTop>=arrH[i-1]&&this.scrollTop<arrH[i])
currentIndex=i-1;
}
lLi.forEach(li=>{
li.classList.remove('active');
})
lLi[currentIndex].classList.add('active')
})
//点击左侧,右侧滚动
for(let i=0;i<lLi.length;i++){
lLi[i].addEventListener('click',function(){
lLi.forEach(li=>{
li.classList.remove('active');
})
this.classList.add('active')
rbox.scrollTop=arrH[i];
})
}
</script>
</html>
一个很简单的电梯导航栏
于 2022-11-03 15:31:45 首次发布