JavaScript—封装animte动画函数

封装Animte 动画函数

虽然可能以后的开发中可能根本不需要自己写,Jquery 给我们封装好了,或者用CSS3的一些属性达到这样的效果可能更简单。

我比较喜欢底层的算法实现,万变不离其中,这个逻辑思路,也是需要锻炼的。也跟着做了一遍

    ///动画函数
    //element:元素
    //target:最后停止的位置
    function animte(element, target) {

        //只有一个Timeid定时器在执行
        if (element,timerId) {
            clearInterval(element.timerId)
            element.timerId = null
        }

        //定时器 每隔多少触发
        element.timerId = setInterval(function ()
            {
            const step=6              //步进
            const current=element.offsetLeft//盒子现在的位置

            //如果现在位置>目标位置 则是向左移动 left为负数
            if (current>target) {
                step = - Math.abs(step)
            }

            //当快到达目标位置时则停止计时器
            if (Math.abs(current-target)<=Math.abs(step)) {
                //停止/
                clearInterval(element.timerId)
                element.style.left = target + 'px'
                //退出函数
                return;
            }
            element.style.left = (current + step) + 'px';
        }, 30)
    }

  

猜你喜欢

转载自www.cnblogs.com/ruogu/p/10804463.html
今日推荐