动画函数封装

116 阅读1分钟

动画函数封装 步长公式

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      width: 200px;
      height: 200px;
      background-color: pink;
      position: relative;
    }

    span {
      width: 150px;
      height: 150px;
      background-color: red;
      position: absolute;
    }
  </style>
</head>

<body>
  <div></div>
  <span></span>
</body>

</html>
<script>
  var div = document.querySelector('div')
  // 封装动画
  function animate(obj, target) {
    // 清除定时器 只保持一个定时器运行
    clearInterval(obj.timer)
    obj.timer = setInterval(() => {
      // 如果到达目标位置 停止定时器
      if (obj.offsetLeft >= target) {
        clearInterval(obj.timer)
      }
      // 移动距离 = 初始位置 + 要移动的距离
      obj.style.left = obj.offsetLeft + 10 + 'px'
    }, 30);
  }
  animate(div, 400)

  // 封装缓动
  var span = document.querySelector('span')

  function slow(obj, target, callback) {
    //  清除定时器
    clearInterval(obj.timer)
    obj.timer = setInterval(() => {
      // 步长取整 步长公式(目标要移动的位置-当前位置)/10
      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'
    }, 30);
  }

  slow(span, 800)
</script>