震惊!运动函数原来是如此运动的

120 阅读1分钟

今天,我们来写一下简单版本的运动函数

以下是我们的css样式 一切从简 从了解功能入手 更适合小白

  <style>
   * {
        margin: 0;
        padding: 0;
    }

    div {
        width: 200px;
        height: 200px;
        background-color: blue;
        position: absolute;
        top: 0;
        left: 0;
    }
</style>

我们的html部分 只需要简单写个div即可了

我们的重头戏还得是js部分

     // 获取标签对象
    let oDiv = document.querySelector('div');

    // 设置运动函数
    // ele  代表函数的指向
    // options 代表存储参数的对象
    // fn 代表回调函数
    function move(ele, options, fn) {

        // 设置计数器
        let count = 0;

        // 循环遍历我们的对象
        for (let key in options) {

            let type = key;

            let num = options[key];

            // 循环执行一次 计数器累加 记录次数
            count++;
            console.log(count);

            // 设置定时器

            const timer = setInterval(() => {

                // 获取初始值
                let init = parseInt(window.getComputedStyle(ele)[type]);

                // 获取步长
                let duration = (num - init) / 5;

                // 步长的容错 
                //因为像素的最小单位是1px 低于1px无法进行操作 
                //所以我们将正小数向上取整 负小数向下取整
                duration > 0 ? duration = Math.ceil(duration) : duration = Math.floor(duration)

                // 判断初始值是否等于实参的值
                if (init === num) {

                    clearInterval(timer);

                    // 完成操作 将计数器清除一次
                    count--;

                    if (count === 0) {

                        // 调用回调函数
                        fn()

                    }
                } else {
                    // 如果不满足条件 继续循环 步长继续进行累加
                    ele.style[type] = init + duration + 'px'
                }


            }, 50)

        }

    }

    // 设置点击事件 调用运动函数
    oDiv.onclick = function () {

        //move 第二个参数为存储参数的对象
        move(this, {
            top: 100,
            left: 200
        }, () => {
            oDiv.style.backgroundColor = 'green'
        })
    }

以上就是我们运动函数的操作过程了 小编创作不易 如果对您有帮助请点个赞 您的支持是我更新最大的动力!!