function animate(obj,json){
//timer是在主函数里面定义的控制定时器的变量 var timer=null
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var flag = true;
for(var attr in json){
//1.获取当前属性
if(attr=="opacity"){
current = Math.round(parseInt(getStyle(obj,attr)*100)) || 0;
}else{
current = parseInt(getStyle(obj,attr));
}
//2.计算步长
var step = (json[attr] - current)/10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
//3.得到目标位置
obj.style[attr] = current + step + "px" ;
console.log(step);
if(current!=json[attr]){
flag = false;
}
}
//4.停止定时器(用flag控制,保证要控制的属性都已经达到标准才停止定时器)
if(flag){
clearInterval(obj.timer);
}
},30);
}
//返回当前的样式(返回值有单位) 兼容性写法可以得到内嵌或者外链的样式
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return window.getComputedStyle(obj,null)[attr];
}
}
如果在主函数里调用,只要传递参数就可以,如:
animate(box,{width:500,left:200});//第一个参数是执行的主体;第二个参数是json字符串,用来控制运动的目标位置