如何实现回到顶部

时间:2022-11-17 23:08:46

转载自:http://www.cnblogs.com/foodoir/p/5885174.html

完整代码:

<!DOCTYPE
html>
<html>     <head>         <meta charset="UTF-8">         <title>Javascript 回到顶部效果</title>         <style type="text/css">             #btn {                 width: 40px;                 height: 40px;                 position: fixed;                 display: none;                 right: 0px;                 bottom: 30px;                 background: url(2.jpg) no-repeat left top;             }                           #btn:hover {                 background: url(2.jpg) no-repeat 0 -40px;             }                           .box {                 width: 1190px;                 margin: 0 auto;             }         </style>     </head>       <body>         <div class="box">             <img src="1.jpg" />         </div>         <a href="javascript:;" id="btn" title="回到顶部"></a>                           <script type="text/javascript">             window.onload = function() {                 var obtn = document.getElementById('btn');                 var timer = null;                 var isTop = true;                 //获取页面的可视窗口高度                 var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;                   //滚动条滚动时触发                 window.onscroll = function(){                     //在滚动的时候增加判断                     var osTop = document.documentElement.scrollTop || document.body.scrollTop;//特别注意这句,忘了的话很容易出错                     if (osTop >= clientHeight) {                         obtn.style.display = 'block';                     }else{                         obtn.style.display = 'none';                     }                       if (!isTop) {                         clearInterval(timer);                     }                     isTop = false;                 };                     btn.onclick = function(){                       //设置定时器                     timer = setInterval(function(){                         //获取滚动条距离顶部的高度                         var osTop = document.documentElement.scrollTop || document.body.scrollTop;  //同时兼容了ie和Chrome浏览器                                                   //减小的速度                         var isSpeed = Math.floor(-osTop / 6);                         document.documentElement.scrollTop = document.body.scrollTop = osTop + isSpeed;                         //console.log( osTop + isSpeed);                           isTop = true;                           //判断,然后清除定时器                         if (osTop == 0) {                             clearInterval(timer);                         }                     },30);                                                                                   };             }         </script>     </body>   </html>