<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>回到顶部效果</title> <style> .box{ width: 1190px; margin: 0 auto; } #btn{ width: 40px; height: 40px; position: fixed; left: 50%; margin-left: 610px; bottom: 30px; background: url("images/top_bg.png") no-repeat left top; display: none; /*首先隐藏回到顶部按钮*/ } #btn:hover{ background: url("images/top_bg.png") no-repeat left -40px; /*-40解决了点击换背景的问题*/ } </style> <script> window.onload=function(){ var obtn=document.getElementById('btn'); //获取页面可视区的高度 var clientHeight=document.documentElement.clientHeight; var timer=null; var isTop=true; //滚动条滚动时触发 window.onscroll=function(){ var osTop=document.documentElement.scrollTop || document.body.scrollTop; if (osTop>=clientHeight){ obtn.style.display='block'; } else { obtn.style.display='none'; } if (false){ clearInterval(timer); } isTop=false; } obtn.onclick=function(){ //设置定时器 timer=setInterval(function(){ //获取滚动条距离顶部的高度 var osTop=document.documentElement.scrollTop || document.body.scrollTop; /*为了兼容浏览器*/ var ispeed=Math.floor(-osTop/5); /*负号为了防止不能到顶部留有间隙*/ document.documentElement.scrollTop = document.body.scrollTop =osTop+ispeed; isTop=true; if (osTop==0){ clearInterval(timer); } },30); } } </script> </head> <body> <div class="box"> <img src="images/tb_bg.jpg"> </div> <a href="javascript:;" id="btn" title="回到顶部"></a> </body> </html>
回到顶部效果
最新推荐文章于 2025-02-11 17:54:53 发布