置顶功能:
一般常见于移动端。当我们浏览某页面时,向下滑动距离顶部有一定距离时,会出现一个按钮,点击这个按钮,会平滑的回滚到顶部。
1、首先准备几个容器
<body>
<div class="zd"></div>
<div style="width:100%;height:500px;background-color: red;"></div>
<div style="width:100%;height:500px;background-color: green;"></div>
<div style="width:100%;height:500px;background-color: yellow;"></div>
<div style="width:100%;height:500px;background-color: blue;"></div>
<div style="width:100%;height:500px;background-color: white;">
</div>
<!--
1. zd是一个回滚到顶部的按钮
2. 其它的div则是模拟的页面内容
-->
</body>
2、写一些样式
html,
body {
height: 100%;
}
.zd {
position: fixed;
bottom: 50px;
right: -55px;
width: 50px;
height: 50px;
background-color: rgba(19, 117, 182, .8);
border-radius: 10px;
text-align: center;
line-height: 50px;
font-size: 25px;
color: aliceblue;
cursor: pointer;
user-select: none;
transition: all 0.5s;
}
.zd:hover {
color: rgb(35, 187, 15);
}
3、监听滚动事件
当发生滚动时,我们需要让按钮显示。
按钮显示条件:
scrollTop:滑动的距离 大于 0 时显示
addEventListener:事件监听
window.addEventListener('scroll', function () {
if (document.documentElement.scrollTop > 0) {
zd.style.right = 5 + 'px';
} else {
zd.style.right = -55 + 'px';
}
})
4、按钮显示的时候,单击按钮回滚到顶部
//获取按钮的dom节点
var zd = document.querySelector(".zd");
//给这个节点监听一个点击事件
zd.addEventListener('click', function () {
//给一个定时器,有过度效果
var time = setInterval(function () {
let top = pageYOffset;
let step = Math.ceil(top / 50);
window.scroll(0, top - step);//进行平滑
//如果到达顶部,清除定时器
if (top == 0) {
clearInterval(time);
}
})
}, 30)