timg.gif
基础版:
//缓动动画 = (目标位置-现在位置)/ 10

function move(obj,end) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
            if (obj.offsetLeft >=end){
                clearInterval(obj.timer);
            }else{
                obj.style.left = obj.offsetLeft + (end - obj.offsetLeft) / 10 +'px';
            }
        },30)
    }

优化:

function move(obj,end) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
            if (obj.offsetLeft >=end){
                clearInterval(obj.timer);
            }else{
                var step = (end - obj.offsetLeft) / 10; //计算出步长
                //因为会出现小数需要取整 当向前走时需要向上取整 当向后走时需要向下取整
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                obj.style.left = obj.offsetLeft + step +'px';
            }
        },30)
    }
Last modification:February 13th, 2020 at 01:31 pm