当页面内容很多的时候,用户可能会一直往下滑动页面。但是当他想返回页面顶部进行其他操作时,他可能需要不断滚动鼠标滚轮,这就导致用户体验将很差。鉴于这种情况, “回到顶部”这一功能便出现了。
<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>
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有