原生JS回到顶部

在学习回到顶部之前先复习定时器:

var n = 0;
setInterval 重复执行
var timer = window.setInterval(function(){
              n++;
              if(n===5){
                     clearInterval(timer);
               }
              console.log(n);
          },1000);
setTimeout 只执行一次
var timer1 = window.setTimeout(function(){
               n++;
               console.log(n);
             },1000);
利用递归实现setTimeout重复执行
var timer2 = null;
function move(){
            clearInterval(timer2);
            n++;
            console.log(n);
            if(n===5){
                return;
            }
           timer2 = window.setTimeout(move,1000);
 }
move();

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>回到顶部scrollTop</title>
    <style type="text/css">
        #button{width: 50px;height: 50px;border-radius: 50%;background: #000;opacity: 0.4;position: fixed;bottom: 30px;right: 30px;display: none;}
        .content{background:-webkit-gradient(linear, 0 0, 0 100%, from(green), to(yellow));height: 2000px;width: 100%;}
    </style>
    
</head>
<body>
<div id="button"></div>
<div class="content"></div>
<script>
   // 回到顶部scrollTop
   // 总时间(duration):500ms
   //频率(interval):多长时间走一步 10ms
   //总距离(target):当前的位置(当前的scrollTop值)目标位置0;
   // 步长(step):每一次走的距离  target/duration * interval 每一次走的距离
  
   var button = document.getElementById("button");
   window.onscroll = computedDisplay;
   function computedDisplay(){
      var curTop = document.documentElement.scrollTop || document.body.scrollTop;
      var curHeight = document.documentElement.clientHeight || document.body.clientHeight;
      button.style.display = curTop>curHeight?"block":"none";
   }
   button.onclick = function(){
      this.style.display = "none";
      window.onscroll = null;
      var duration = 500,interval = 10,target = document.documentElement.scrollTop || document.body.scrollTop;
      var step = (target/duration) * interval;

      var timer = window.setInterval(function(){
           var curTop = document.documentElement.scrollTop || document.body.scrollTop;
           if(curTop ===0){
             window.clearInterval(timer);
             window.onscroll = computedDisplay;//动画结束后方法重新绑定
             return;
           }
           curTop -=step;
           document.documentElement.scrollTop = curTop;
           document.body.scrollTop = curTop;
      },interval);

   }

</script>
</body>
</html>

 

posted @ 2016-10-17 17:07  wenjia001  阅读(432)  评论(0编辑  收藏  举报