<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> * { margin: 0; padding: 0; font-family: "微软雅黑"; font-size: 14px; -webkit-user-select: none; } html, body { width: 100%; height: 500%; background: #11C900; /*css3背景颜色渐变效果*/ background: -webkit-linear-gradient(top, #11C900, lightgreen, lightblue, lightcoral, lightgoldenrodyellow, lightgoldenrodyellow, lightsalmon, lightseagreen, lightslategrey); background: linear-gradient(top, #11C900, lightgreen, lightblue, lightcoral, lightgoldenrodyellow, lightgoldenrodyellow, lightsalmon, lightseagreen, lightslategrey); } a { text-decoration: none; color: #000; } a:hover, a:active, a:target, a:visited { text-decoration: none; color: #000; } #goLink { display: none; position: fixed; /*说只要加了position,元素自己就变成了块状*/ bottom: 200px; right: 50px; width: 50px; height: 50px; line-height: 50px; text-align: center; background: red; border-radius: 50%; opacity: 0.2; filter: alpha(opacity=20); } #goLink:hover { opacity: 1; filter: alpha(opacity=100); } </style> </head> <body> <!--A标签本身是跳转页面的,把跳转的地址写在href这个属性中,不写值的话是刷新本页面,写了#xxx的话是锚点定位,定位到xxx处,写成"javascript:;"是取消a标签默认跳转的行为--> <a href="javascript:;" id="goLink">Go</a> <script type="text/javascript"> var goLink = document.getElementById("goLink"); //回到顶部: //总时间(duration):500ms //频率(interval):多长时间走一步 10ms //总距离(target):当前的位置(当前的scrollTop)-目标的位置(0) //步长(step):每一次走的距离 target/duration*interval //开始Go按钮是不显示,只有当浏览器卷去的高度超过一屏幕的高度的时候显示,反之隐藏->只要浏览器的滚动条在滚动,我们就需要判断GO显示还是隐藏 //浏览器滚动条滚动:拖动滚动条、鼠标滚轮、键盘上下键或者pageDown、pageUp、点击滚动条的空白处或者箭头(自主操作行为)。。。我们还可通过js控制scrollTop的值实现滚动条的滚动 window.onscroll = computedDisplay; function computedDisplay() { var curTop = document.documentElement.scrollTop || document.body.scrollTop; var curHeight = document.documentElement.clientHeight || document.body.clientHeight; goLink.style.display = curTop > curHeight ? "block" : "none"; } goLink.onclick = function () { //当点击的时候让当前的GO消失 this.style.display = "none";//光这样还不行,我们往回走的时候又把window.onscroll的行为触发了,让go又显示了->我们需要在点击后,把window.onscroll绑定的事件取消掉 window.onscroll = null; //当我点击go的时候,首先把每一步要走的步长计算出来 var duration = 500, interval = 10, target = document.documentElement.scrollTop || document.body.scrollTop; var step = (target / duration) * interval; //计算完成步长后,让当前的页面每隔interval这么长的时间走一步:在上一次scrollTop的基础上-步长 var timer = window.setInterval(function () { var curTop = document.documentElement.scrollTop || document.body.scrollTop; if (curTop === 0) {//已经到头了 window.clearInterval(timer); window.onscroll = computedDisplay;//当动画结束后还需要把对应的方法重新绑定为window.onscroll return; } curTop -= step; document.documentElement.scrollTop = curTop; document.body.scrollTop = curTop; }, interval) } </script> </body> </html>
JS回到顶部按钮实现源代码
最新推荐文章于 2025-05-26 23:59:04 发布