js开发 简答动画函数封装


//封装行数 obj目标对象   target 目标位置

function animate(obj,target){
   //obj是已有对象, 直接赋值变量将会重新开辟空间 避免浪费内存空间 给obj添加一个属性
   // obj.timer
    obj.timer = setInterval(function(){
          if (obj.offsetLeft >= target){
              //清除定时器
              clearInterval(obj.timer);
    }
     obj.style.left = obj.offsetLeft + 1 + 'px';
    },30);
}

var div =document.querySelector('div');
var span = document.querySelector('span');

//调用函数
animate(div,300);
animate(span,200)

相关