<!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>
回到頂部效果
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.