简单动画函数封装及缓动效果

168 阅读1分钟
function animate(obj, target) {
 			clearInterval(obj.timer);
			 //obj.timer = setInterval(function() {
            var timer = setInterval(function() {
                if (obj.offsetLeft >= target) {
                    clearInterval(timer);
                }
                obj.style.left = obj.offsetLeft + 1 + 'px';

            }, 30);
            // 时间间隔,偏移距离可自行设置
          }

//animate(obj,target);

缓动效果

function animate(obj, target) {
            clearInterval(obj.timer);
            obj.timer = setInterval(function() {
                var step = (target - obj.offsetLeft) / 10;
                // 把我们步长值改为整数 不要出现小数的问题,
                //前进往大取整Math.ceil,后退往小取整Math.floor
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if (obj.offsetLeft >= target) {
                    // 停止动画 本质是停止定时器
                    clearInterval(timer);
                }
                obj.style.left = obj.offsetLeft + step + 'px';

            }, 30);
        }