缓冲运动的封装--简易.js

<!DOCTYPE html>
<html lang="en">
   <head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document</title>
   <style>

          .box1{100px;height:100px;background: red;position: absolute;left:0;top:0;}
          .box2{100px;height:100px;background: blue;position: absolute;left:0;top:130px;}

           .line{1px;height:600px;background: black;position: absolute;top:0;left:500px;}

  </style>
  </head>
  <body>
        <div class="box1"></div>
        <div class="box2"></div>
        <div class="line"></div>
    </body>
   <script>

          var obox1 = document.querySelector(".box1");
         var obox2 = document.querySelector(".box2");

         document.onclick = function(){
                move(obox1,{left:600,top:30},function(){
                 move(obox2,{400,height:120})
           });
         }


        function move(ele,data,end){
             clearInterval(ele.t);
             ele.t = setInterval(() => {
            // 1.计时器开启之后,设定状态为关闭计时器
              var onoff = true;
             for(var i in data){
             var iNow = parseInt(getStyle(ele,i));
             var speed = (data[i] - iNow)/7;
              speed = speed<0 ? Math.floor(speed) : Math.ceil(speed);
// 必须所有属性都到目标才能清计时器
// 每次只能拿到一个属性
// 只能判断一个属性是否到目标
// 如果有一个属性到目标了,一定会清除计时器么?不一定
// 如果有一个属性没到目标,一定不清除计时器!!!

              if(data[i] != iNow){
// 3.但是在设定状态之后,关闭计时器之前,判断是否有属性没到目标,只要有一个属性没到目标,就把状态改成不关闭计时器
              onoff = false;
            }
             ele.style[i] = iNow + speed + "px";
            }
// 2.根据状态决定关闭计时器
            if(onoff){
           clearInterval(ele.t);

    end && end();
    }
    }, 30);
  }

    function getStyle(ele,attr){
      if(getComputedStyle){
      return getComputedStyle(ele,false)[attr];
    }else{
      return ele.currentStyle[attr];
    }
  }
  </script>
  </html>

原文地址:https://www.cnblogs.com/wss521/p/12039134.html