前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >网站经典功能之返回顶部

网站经典功能之返回顶部

作者头像
很酷的站长
发布于 2022-12-16 13:05:45
发布于 2022-12-16 13:05:45
86300
代码可运行
举报
运行总次数:0
代码可运行
1. 背景介绍

当页面内容很多的时候,用户可能会一直往下滑动页面。但是当他想返回页面顶部进行其他操作时,他可能需要不断滚动鼠标滚轮,这就导致用户体验将很差。鉴于这种情况, “回到顶部”这一功能便出现了。

站长源码网

2. 返回顶部代码示例

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<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>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验