// 参数:
// obj:要执行动画的对象;
// attr:要执行动画的样式,如"left" "top" "height" "width"
//target: 执行动画的目标位置
//speed:移动的速度
//callback:回调函数,将在动画执行完毕后执行
// var timer;
function move(obj,attr,target,speed,callback){
clearInterval(obj.timer);//关闭上一个定时器
var current = parseInt(getStyle(obj,attr));//获取obj当前位置
if(current > target){
speed = - speed;//如果当前位置大于目标位置,应该向左移动,速度为负值
}
obj.timer = setInterval(function(){
var oldValue = parseInt(getStyle(obj,attr));//获取obj原来的位置
var newValue = oldValue + speed;//设置obj移动
if((speed < 0 && newValue < target) || (speed > 0 && newValue > target)){
newValue = target;//不能让移动超过边界
}
obj.style[attr] = newValue + "px";//设置obj现在的位置
if(newValue == target){//如果obj到达目标位置,则停止移动,清除定时器
clearInterval(obj.timer);
callback && callback();
}
},30);
};
function getStyle(obj,name){
if(window.getComputedStyle){
return getComputedStyle(obj,null)[name];
}else{
return obj.currentStyle[name];
};
}