Javascript 特效(一)返回顶部

时间:2021-02-24 14:54:15
 1 <!doctype html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>无标题文档</title>
 6 <style type="text/css">
 7 *{ margin:0; padding:0;}
 8 body{ height:2000px;}
 9 #box{ width:40px;  height:40px; display:none; position:fixed; right:30px; bottom:30px; background:#f00;}
10 </style>
11 <script type="text/javascript">
12 window.onload=function(){
13     var oBox=document.getElementById("box");
14     var clientHeight=document.documentElement.clientHeight;
15     var timer=null;
16     var onOff=true;
17     
18     window.onscroll=function(){
19         var osTop=document.documentElement.scrollTop || document.body.scrollTop;
20         
21         if(osTop>=clientHeight){
22             oBox.style.display='block';
23         }else{
24             oBox.style.display='none';
25         };
26         
27         if(!onOff){
28             clearInterval(timer);
29         };
30         onOff=false;
31     };
32     
33     oBox.onclick=function(){
34         
35         timer=setInterval(function(){
36             var osTop=document.documentElement.scrollTop || document.body.scrollTop;
37             var iSpeed= Math.floor(-osTop/6);
38             var i=document.documentElement.scrollTop = document.body.scrollTop = osTop + iSpeed;
39             
40             onOff=true;
41             if(osTop ==0){
42                 clearInterval(timer);
43             }
44         },30);
45     };
46 };
47 </script>
48 </head>
49 
50 <body>
51 <div id="box"></div>
52 </body>
53 </html>