欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript实现回到顶部功能

程序员文章站 2022-05-07 21:25:42
html代码

css代码 * { margin: 0;...

html代码

<p id="box"></p>  

css代码

* {  
           margin: 0;  
           padding: 0;  
       }  
  
       body {  
           height: 3000px;  
       }  
  
       #box {  
           width: 100px;  
           height: 100px;  
           background: red;  
           position: absolute;  
           right: 0;  
       }  

JS代码

var oBox = document.getElementById("box");  
   var timer = null;  
   var iH = document.documentElement.clientHeight;  
   oBox.style.top = iH / 2 - oBox.offsetHeight / 2 + "px";  
   document.onscroll = function () {  
       var iT = document.documentElement.scrollTop || document.body.scrollTop;  
       var iTarget = Math.round(iH / 2) - Math.round(oBox.offsetHeight / 2) + iT;  
  
       move(oBox, iTarget);  
   };  
  
   function move(obj, iTarget) {  
       clearInterval(timer);  
       timer = setInterval(function () {  
           var speed = (iTarget - obj.offsetTop) / 8;  
           speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);  
  
           if (obj.offsetTop == iTarget) {  
               clearInterval(timer);  
           } else {  
               obj.style.top = obj.offsetTop + speed + 'px';  
           }  
       }, 30)  
   }