缓动动画添加回调函数

Tutorial: DOM操作 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0
<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      span {
        position: absolute;
        left: 0;
        top: 200px;
        display: block;
        width: 150px;
        height: 150px;
        background-color: purple;
      }
    </style>
  </head>

  <body>
    <button class="btn500">点击夏雨荷到500</button>
    <button class="btn800">点击夏雨荷到800</button>
    <span>夏雨荷</span>

    <script>
      function animate(obj, target, callback) {
        // console.log(callback);  callback = function() {}  调用的时候 callback()

        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
          var step = (target - obj.offsetLeft) / 10;
          step = step > 0 ? Math.ceil(step) : Math.floor(step);

          if (obj.offsetLeft == target) {
            clearInterval(obj.timer);

            // 回调函数写到定时器结束里面
            if (callback) {
              // 调用函数
              callback();
            }
          }

          obj.style.left = obj.offsetLeft + step + "px";
        }, 15);
      }

      var span = document.querySelector("span");
      var btn500 = document.querySelector(".btn500");
      var btn800 = document.querySelector(".btn800");

      btn500.addEventListener("click", function () {
        // 调用函数
        animate(span, 500);
      });

      btn800.addEventListener("click", function () {
        // 调用函数
        animate(span, 800, function () {
          span.style.backgroundColor = "red";
        });
      });
    </script>
  </body>
</html>