跳楼机介绍
一个页面当内容过多的时候,会在页面上给跳转到不同页面的相关链接,把这个技术称为页面跳楼机。例如京东页面右侧存在的快速导航链接。
跳楼机实现
<!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;
}
.container {
width: 1000px;
margin: 0 auto;
}
.container div {
height: 400px;
margin-top: 20px;
background-color: #ccc;
font-weight: bold;
}
.floor {
position: fixed;
bottom: 50px;
width: 50px;
right: 50px;
background-color: #fa0;
}
.floor span {
display: block;
font-size: 14px;
padding: 8px;
border-bottom: 1px solid #fff;
text-align: center;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<div class="box1">时尚达人</div>
<div class="box2">儿童装</div>
<div class="box3">幼儿用品</div>
<div class="box4">老年装</div>
<div class="box5">户外用品</div>
</div>
<div class="floor">
<span>时尚达人</span>
<span>儿童装</span>
<span>幼儿用品</span>
<span>老年装</span>
<span>户外用品</span>
</div>
<script>
/**
* 需求:js完成跳楼机效果
* 分析:
* 1、获取页面上span按钮,绑定点击事件
* 2、获取页面需要跳转到的每个div距离屏幕顶部的位置,
* 3、设置滚动条的位置
*/
let span = document.querySelectorAll(".floor span");
let div = document.querySelectorAll(".container div");
span.forEach(function (v, i) {
v.addEventListener("click", function () {
scrollTo({
// 获取对应的div距离屏幕顶部的距离
top: div[i].offsetTop,
// 设置滚动条滚动时的动画效果
// behavior 类型String,表示滚动行为,
// 支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值auto,
behavior: "smooth"
})
})
})
</script>
</body>
</html>
测试效果:由于页面较大,只能截取部分,可以把上面代码全部拷贝过去,直接运行测试效果