正则案例:运动函数

53 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }
    .box {
      width: 200px;
      height: 200px;
      background-color: aquamarine;
      position: absolute;
      top: 0px;
      left: 0px;
    }
  </style>
</head>
<body>
  <div class="box"></div>
  <script>
    /**
     * 回调函数
     *    本质上就是一个函数
     *        1. 把函数A, 以实参的形式传递到函数B内部
     *        2. 在函数B内部,以形参的方式调用函数A
     *        3. 此时我们可以把函数A叫做函数B的回调函数
     * */ 
    var box = document.querySelector('.box')
    box.onclick = function() {
      // 运动函数的开始
      move(this, {
        left: 100,
        top: 100,
        width:400,
        height:300
      }, () => {
        // console.log('我是一个回调函数')
        box.style.backgroundColor = 'red'
      })
      // 运动函数结束了

    }
    function move (ele, options ,fn) {
      // 创建一个变量作为计数器
      let count = 0
      for(let key in options) {
        let type = key
        let target = options[key]
        // 循环每执行一次,让计数器自增一次,因为循环执行一次说明要开启一个 运动
        count++
        // 1.开启定时器
        const timer = setInterval(() => {
          // 2.获取当前位置  
          let init = parseInt(window.getComputedStyle(ele)[type])
          // 3.计算本次移动距离 (目标 - 当前值) / 10
          let duration = (target - init) / 10
          duration = duration > 0 ? Math.ceil(duration) : Math.floor(duration)
          // 5.判断走还是不走
          if(target === init) {
            clearInterval(timer)
            // 每清楚一个定时器,说明有一个运动函数结束了,所以我们将count--
            count--
            if(count === 0) {
              // 当前分支执行,说明所有的运动函数全都执行完毕了
              // console.log('说明所有的运动函数全部都结束了')
              fn()
            }
          } else {
            // 元素原本的位置 + 要移动的距离,然后赋值给元素
            ele.style[type] = init + duration + 'px' 
          }
        }, 20)
      }
    }
  </script>
</body>
</html>