

当页面内容很多的时候,用户可能会一直往下滑动页面。但是当他想返回页面顶部进行其他操作时,他可能需要不断滚动鼠标滚轮,这就导致用户体验将很差。鉴于这种情况, “回到顶部”这一功能便出现了。
站长源码网
<style>
div.box {
height: 1000px;
background-color: aqua;
margin-bottom: 20px;
}
div#gotop {
width: 30px;
height: 30px;
cursor: pointer;
border-radius: 4px;
background-color: #4c4c4c;
position: fixed;
right: 30px;
bottom: 60px;
}
div#gotop img {
width: 100%;
height: 100%;
}
</style>
<div class="box"></div>
<div class="box"></div>
<div id="gotop">
<img src="https://www.itqaq.com/static/index/plugin/fixed/images/top.png">
</div>
<script>
window.onscroll = () => {
const res = document.body.scrollTop || document.documentElement.scrollTop
const gotop = document.getElementById('gotop')
gotop.style.display = res > 400 ? 'block' : 'none'
}
gotop.onclick = () => {
let res = document.body.scrollTop || document.documentElement.scrollTop
let t = res / 60
const index = setInterval(() => {
res -= t
if (res < 0) {
res = 0
clearInterval(index)
}
document.body.scrollTop = res
document.documentElement.scrollTop = res
}, 5);
}
</script>