jQuery回到顶部
回到顶部
如果是一瞬间回到顶部,那很简单,但是如果想要平滑的回到顶部,那我们可以先计算出当前滚动条和顶部的位置,然后设置一个时间,表示在这个时间点到达顶部,并且是分多次的,每次设置一定的时间,计算出每次距离之后定时往顶部拉进距离。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>03_回到顶部</title> <style> #to_top { width: 30px; height: 40px; font: 14px/20px arial; text-align: center; background: #06c; position: fixed; cursor: pointer; color: #fff; left: 1050px; top: 500px; } </style> </head> <body style="height: 2000px;"> <div style="border:1px solid black;width:100px;height:150px;overflow:auto"> This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. his is some text. </div> <br> <br> <br> <button id="btn1">得到scrollTop</button> <button id="btn2">设置scrollTop</button> <div id="to_top">返回顶部</div> <script type="text/javascript" src="jquery-1.10.1.js"></script> <script type="text/javascript"> $('#to_top').click(function () { // 瞬间滚到顶部,直接定义距离为0,没什么特效 //$('html,body').scrollTop(0) // 平滑滚到顶部 // 总距离 var $page = $('html,body') //兼容chrome和ie,获取滚动条当前距离顶部的距离 var distance = $('html').scrollTop() + $('body').scrollTop() // 总时间 var time = 500 // 间隔时间 var intervalTime = 50 //单元移动的距离,每一次移动的距离 //一共需要移动的次数=(time/intervalTime) //每次需要移动的距离=distance/(time/intervalTime) var itemDistance = distance/(time/intervalTime) // 使用循环定时器不断滚动 var intervalId = setInterval(function () { distance -= itemDistance // 到达顶部, 停止定时器 if(distance<=0) { distance = 0 //修正 clearInterval(intervalId) } $page.scrollTop(distance) }, intervalTime) }) </script> </body> </html>
界面:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术