JS---變速動畫函數封裝

變速動畫函數封裝

 

勻速動畫:每次步數都是10 (var step=10;)html

變速(緩動)動畫:每次的步數是用當前位置和目標位置相減 var step=(target-current)/10;函數

 

 

代碼以下:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>title</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    div {
      margin-top: 20px;
      width: 200px;
      height: 100px;
      background-color: green;
      position: absolute;
      left: 0;
      top: 0;
    }
  </style>
</head>

<body>
  <input type="button" value="移動到400px" id="btn1" />
  <input type="button" value="移動到800px" id="btn2" />
  <div id="dv">
    <script src="common.js"></script>
    <script>
      //點擊按鈕移動div

      my$("btn1").onclick = function () {
        animate(my$("dv"), 400);
      };
      my$("btn2").onclick = function () {
        animate(my$("dv"), 800);
      };


      //變速動畫函數

      function animate(element, target) {
        //清理定時器
        clearInterval(element.timeId);
        element.timeId = setInterval(function () {
          //獲取元素的當前位置
          var current = element.offsetLeft;
          //移動步數
          var step = (target - current) / 10;
          step = step > 0 ? Math.ceil(step) : Math.floor(step);
          current += step;
          element.style.left = current + "px";
          if (current == target) {
            //清理定時器
            clearInterval(element.timeId);
          }
          //測試代碼
          console.log("目標位置:" + target + ",當前位置:" + current + ",步數:" + step);
        }, 20);
      }

    </script>
  </div>
</body>

</html>
相關文章
相關標籤/搜索