window.onload=function(){
var aDiv=document.getElementsByTagName('div');
for(i=0;i<aDiv.length;i++){
aDiv[i].timer=null;
aDiv[i].onmouseover=function(){
startmove(this,400);
}
aDiv[i].onmouseout=function(){
startmove(this,100);
}
}
}
function startmove(obj,iTarget){
clearInterval(obj.timer);
var speed=(iTarget-parseInt(getStyle(obj,'width')))/10;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
obj.timer=setInterval(function(){
if(parseInt(getStyle(obj,'width'))==iTarget){
clearInterval(obj.timer);
}else{
obj.style.width=parseInt(getStyle(obj,'width'))+speed+'px';
}
},30)
}
function getStyle(obj,attr){
if(obj.currentStyle){//currentStyle针对IE浏览器
return obj.currentStyle[attr];
}else{
//getComputedStyle针对火狐浏览器
return getComputedStyle(obj,false)[attr];
}
}
代码如下:
function startmove(obj, iTarget) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var speed = (iTarget - parseInt(getStyle(obj, 'width'))) / 10;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (parseInt(getStyle(obj, 'width')) == iTarget) {
clearInterval(obj.timer);
} else {
obj.style.width = parseInt(getStyle(obj, 'width')) + speed + 'px';
}
}, 30)
}
var speed = (iTarget - parseInt(getStyle(obj, 'width'))) / 10; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
这两句要放在obj.timer = setInterval(function () {里面,代码如下:
function startmove(obj, iTarget) { clearInterval(obj.timer); obj.timer = setInterval(function () { var speed = (iTarget - parseInt(getStyle(obj, 'width'))) / 10; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if (parseInt(getStyle(obj, 'width')) == iTarget) { clearInterval(obj.timer); } else { obj.style.width = parseInt(getStyle(obj, 'width')) + speed + 'px'; } }, 30) }