JavaScript封装动画函数优化,解决点击按钮创建多个定时器的问题

 //动画函数
    function animate(element, target) {
        //先清理定时器
        clearInterval(element.tinmeId);
        //一会要清理定时器(只产生一个定时器)
        element.tinmeId = setInterval(function () {
            //获取div当前的位置
            var current = element.offsetLeft;//数字类型没有px
            //div每次移动多少像素-----步数
            var step = 10;
            step = current < target ? step : -step;
            //每次移动后的距离
            current += step;
            //判断当前移动后的位置是否到达目标位置
            if (Math.abs(target - current) > Math.abs(step)) {
                element.style.left = current + "px";
            } else {
                //清理定时器
                clearInterval(element.tinmeId);
                element.style.left = target + "px";
            }
        }, 20)
    }

 

posted @ 2018-08-02 15:23  {颜逸}  阅读(389)  评论(0编辑  收藏  举报