<!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;
}
body{
height: 5000px;
}
.floor{
width: 400px;
height: 400px;
background-color: pink;
margin: 0 auto 20px;
}
ul{
list-style: none;
}
li{
width: 80px;
height: 40px;
text-align: center;
line-height: 40px;
background-color: red;
font-size: 18px;
cursor: pointer;
}
#floorNav{
position: fixed;
right: 20px;
top:50%;
width: 80px;
height: 160px;
margin-top: -80px;
}
.cur{
color: #fff;
}
</style>
</head>
<body>
<section id="floors">
<div class="floor" data-n="科技">
科技
</div>
<div class="floor" data-n="新闻">
新闻
</div>
<div class="floor" data-n="娱乐">
娱乐
</div>
<div class="floor" data-n="体育">
体育
</div>
</section>
<nav id="floorNav">
<ul id="list">
<li data-n="科技" class="cur">科技</li>
<li data-n="新闻">新闻</li>
<li data-n="娱乐">娱乐</li>
<li data-n="体育">体育</li>
</ul>
</nav>
<script>
let offsetTopArr = []
let floors = document.getElementsByClassName("floor");
for(let i = 0 ; i < floors.length; i++){
offsetTopArr.push(floors[i].offsetTop);
}
offsetTopArr.push(Infinity)
// console.log(offsetTopArr)
let list = document.getElementById("list")
let lis = list.getElementsByTagName("li")
list.onclick = function(e){
if(e.target.tagName.toLowerCase() == "li"){
let n = e.target.getAttribute("data-n");
let floor = document.querySelector(".floor[data-n="+ n + "]")
document.documentElement.scrollTop = floor.offsetTop;
}
}
let curFloor = 0;
window.onscroll = function(){
const scrollTop = document.documentElement.scrollTop;
for(var i=0; i<offsetTopArr.length; i++){
if(scrollTop >= offsetTopArr[i] && scrollTop < offsetTopArr[i+1]){
break
}
}
if(curFloor != i){
curFloor = i
for(let j=0;j<lis.length;j++){
if(j==i){
lis[j].className = "cur"
}else{
lis[j].className = ""
}
}
}
}
</script>
</body>
</html>
offsetTop 和 scrollTop 完成楼层导航
最新推荐文章于 2023-03-15 18:28:39 发布