js--定时器--匀速动画,缓动动画

// 匀速动画
function animate(obj, target) {
    clearInterval(obj.tim)
    var newvalue = 0;
    obj.tim = setInterval(function () {
        newvalue = obj.offsetLeft + 5;
        if (newvalue >= target) {
            newvalue=target;
            clearInterval(obj.tim)
        }
        obj.style.left = newvalue + 'px';
    }, 30)

}
// 缓动动画  :(目标值-现在位置)/10
function animate2(obj, target ,callback) {
    console.log('开始');
    clearInterval(obj.tim)
    var newvalue = 0;
    var step = 0;
     obj.tim = setInterval(function () {
        step =(target - obj.offsetLeft) / 10;
        step =step>0?Math.ceil(step):Math.floor(step);
   
        newvalue = obj.offsetLeft + step;
        if (newvalue >= target&&step>0||newvalue <= target&&step<0) {
            newvalue=target;
            clearInterval(obj.tim);
            if(callback){
                callback()
            }
            console.log('结束');
        }
        obj.style.left = newvalue + 'px';
    }, 30)
}

​​​​​​​动画函数的使用




    
    
    
    Document
    


    
<
问题反馈

你可能感兴趣的:(js,javascript,css3,开发语言)