JavaScript封装缓动动画函数

  //缓动动画
    function animate(element, target) {
        //清理定时器
        clearInterval(element.timeId);
        element.timeId = setInterval(function () {
            //获取元素的当前位置
            var current = element.offsetLeft;
            //移动的步数
            var step = (target - current) / 10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            current += step;
            element.style.left = current + "px";
            if (current == target) {
                //清理定时器
                clearInterval(element.timeId);
            }
            //测试代码:
            console.log("目标位置:" + target + ",当前位置:" + current + ",每次移动步数:" + step);
        }, 20);
    }

  

posted @ 2018-08-13 17:30  {颜逸}  阅读(441)  评论(0编辑  收藏  举报