运动函数

42 阅读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>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 100px;
            height: 100px;
            background-color: pink;
            position: absolute;
            top: 0;
            left: 100px;
            opacity: 0.1;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    
    <script>
        function move(el, options, callback) {
            // 函数开启的时候创建一个变量,作为一个计数器
            let num = 0
            for (let key in options) {
                // for...in 循环开始的时候,计数器++,因为这里开始执行就证明马上要开启一个定时器了
                num++
                const type = key
                let target = options[key]
                if(type === "opacity") target *= 100
                const timer = setInterval(() => {
                    let count = type === "opacity" ? window:getComputerStyle(el)[type] * 100 : paeseInt(window.getComputedStyle(el)[type])
                    let duration = (target - count) / 10
                    duration = duration > 0 ? Math.ceil
                    (duration) : Math.floor(duration)
                    
                    if(target === count){
                        clearInterval(timer)
                        每关闭一次定时器,就对我们的计数器--,如果有一次--完毕,计数器的值===初始值,就证明此刻是运动函数真正结束的时候
                        num--
                        if(num === 0) {
                            callback()
                            // 通过回调函数让我们的这个运动函数完毕后的功能更加灵活
                        }
                 } else {
                     el.style[type] = type === "opcity" ? count / 100 + duration / 100 : count + duration + "px"
                 }       
                },20)
             }
          }
          
          box.onclick = function () {
              move(
                  box,
                  {
                      opacity: 1,
                      left: 200,
                      top: 200,
                      width: 400
                  },
                  () => {box.style.backgroundColor = "green"}
              )
          }