引用animate动画函数

Tutorial: DOM实战 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0

引用 animate 动画函数

  • animate.js
function animate(obj, target, 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);
      callback && callback();
    }

    obj.style.left = obj.offsetLeft + step + "px";
  }, 15);
}
  • 引用
<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      .sliderbar {
        position: fixed;
        right: 0;
        bottom: 100px;
        width: 40px;
        height: 40px;
        text-align: center;
        line-height: 40px;
        cursor: pointer;
        color: #fff;
        border: 1px solid red;
      }

      .con {
        position: absolute;
        left: 0;
        top: 0;
        width: 200px;
        height: 40px;
        background-color: purple;
        z-index: -1;
      }
    </style>
    <script src="animate.js"></script>
  </head>

  <body>
    <div class="sliderbar">
      <span></span>
      <div class="con">问题反馈</div>
    </div>

    <script>
      // 1. 获取元素
      var sliderbar = document.querySelector(".sliderbar");
      var con = document.querySelector(".con");

      // 当我们鼠标经过 sliderbar 就会让 con这个盒子滑动到左侧
      // 当我们鼠标离开 sliderbar 就会让 con这个盒子滑动到右侧
      sliderbar.addEventListener("mouseenter", function () {
        // animate(obj, target, callback);
        // 200 - 40 = 160
        animate(con, -160, function () {
          // 当我们动画执行完毕, 就把 ← 改为 →
          sliderbar.children[0].innerHTML = "→";
        });
      });

      sliderbar.addEventListener("mouseleave", function () {
        animate(con, 0, function () {
          sliderbar.children[0].innerHTML = "←";
        });
      });
    </script>
  </body>
</html>