回到頂部有多種實現方式:javascript
1.經過錨點而後定位,這個比較簡單,可是效果比較生硬,就很少解釋了css
2.經過JavaScript實現,用到了定時器,window.onload,window.onscroll,setInterval,clearInterval,document.documentElement.scrollTop||document.body.scrollTop(兼容谷歌火狐)html
原理是經過監聽滾動,得到實時的scrollTop,而後scrollTop-=200(常數),這個也很少說了java
3,經過jQuery實現,今天主要講這個,首先準備一張大圖,附上代碼jquery
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>回到頂部</title> <style type="text/css"> #btn {width:40px; height:40px; position:fixed; right:65px; bottom:10px; display:none; background:url(img/top_bg.png) no-repeat left top;} #btn:hover {background:url(img/top_bg.png) no-repeat 0 -39px;} .bg {width:1190px; margin:0 auto;} </style> <script src="js/jquery-1.7.2.js"></script> <script> $(function(){ var scrollTop=0; $(window).scroll(function(){ scrollTop=$(document).scrollTop(); var H=$(window).height(); if(scrollTop>H){ $('#btn').css({ display:'block' }); }else{ $('#btn').css({ display:'none' }); } }); $('#btn').click(function(){ $('body,html').animate({ scrollTop:0 },1000); }); }); </script> </head> <body> <a href="javascript:;" id="btn" title="回到頂部"></a> <div class="bg"> <img src="img/tb_bg.jpg" alt="" /> </div> </body> </html>