运动函数

94 阅读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>
    *{
      margin: 0;
      padding: 0;
    }
    .box{
      width: 200px;
      height: 200px;
      background-color: pink;
      position: absolute;
      top: 0px;
      left: 0px;
    }
  </style>
</head>
<body>
  <div class="box"></div>
  <script>
    /**
     * 回调函数
     * 本质上就是一个函数
     *  1. 把函数A以实参的形式传递到函数B内部
     * 2.在函数B内部以形参的方式调用函数A
     * 3.此时我们可以把函数A叫做函数B的回调函数
    */
   //0.获取元素
    var box = document.querySelector('.box')

    //1.给元素添加事件
    box.onclick = function(){
      // this.style.left = 500 + 'px'
      // move(this,'left','300')
      // move(this,'top','200')
      move(this,{
        left:100,
        top:100,
        width:400
      },() => {
        box.style.backgroundColor = 'red'
      })

      
    }

    function move(ele,options,fn){
      // console.log(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
        // //4.判断移动距离,如果小于1,向上取整
        // if(duration<1){
        //   duration = Math.ceil(duration)
        // }

        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>