实现楼层的滚动以及点击楼层按钮跳转到对应的楼层,代码如下
html代码:
<div style="height: 500px; background-color: black; color: #fff;">无意义的文本</div>
<div class="layerbox">
<div class="layer num1">第一层</div>
<div class="layer num2">第二层</div>
<div class="layer num3">第三层</div>
<div class="layer num4">第四层</div>
</div>
<div class="nav">
<ul>
<li>1F</li>
<li>2F</li>
<li>3F</li>
<li>4F</li>
</ul>
</div>
<div style="height: 500px; background-color: black; color: #fff;">无意义的文本</div>
css代码:
* {
margin: 0;
padding: 0;
}
.layer {
height: 300px;
font-size: 80px;
color: white;
text-align: center;
}
.num1 {
background-color: red;
}
.num2 {
background-color: blue;
}
.num3 {
background-color: yellow;
}
.num4 {
background-color: green;
}
.nav {
position: fixed;
right: 50px;
bottom: 400px;
background-color: pink;
}
ul {
list-style: none;
}
ul li {
padding: 10px;
width: 50px;
height: 50px;
line-height: 50px;
text-align: center;
border: 1px solid #000;
}
ul li.active {
background-color: crimson;
}
js代码:
<script>
var layers = document.querySelectorAll(".layer")
var lis = document.querySelectorAll('li')
for (let i = 0; i < lis.length; i++) {
const li = lis[i]
li.onclick = function (e) {
//页面的偏移量,原来的页面滚动的距离
var scrollTop = document.documentElement.scrollTop
var offsetTop = layers[i].offsetTop
if (scrollTop > offsetTop) {
// 滚动条向上移动
var timer = setInterval(function () {
if (scrollTop > offsetTop) {
scrollTop -= 40
if (scrollTop - offsetTop < 40) {
// 如果最后一洞的距离小于40时,直接设置偏移量为0
window.scrollTo(0, offsetTop)
} else {
window.scrollTo(0, scrollTop)
}
} else {
clearInterval(timer)
}
}, 50)
} else {
// 滚动条向下移动
// scrollTop <= offsetTop
var timer = setInterval(function () {
if (scrollTop < offsetTop) {
scrollTop += 40
if (offsetTop - scrollTop < 40) {
window.scrollTo(0, offsetTop)
} else {
window.scrollTo(0, scrollTop)
}
} else {
clearInterval(timer)
}
}, 50);
}
}
}
window.onscroll = function (e) {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
layers.forEach(function (v, i) {
if (v.clientHeight + v.offsetTop > scrollTop && scrollTop > v.offsetTop) {
// 滚动的楼层到达顶部范围,离开消失
lis[i].classList.add("active")
} else {
lis[i].classList.remove("active")
}
})
}
</script>