標籤:style blog http java width io
如果只為div添加一個定時器的話,在多個div變寬的時候會發生問題,但是如果為每個div添加一個定時器,那麼就可以實現多個物體變寬。注意:在多物體運動的情況下,所有東西不能共用。offsetXXX會跟border衝突導致不能得到想要的結果,在這裡可以用getStyle()函數代替。
function getStyle(obj, name){if(obj.currentStyle){return obj.currentStyle[name];}else{return getComputedStyle(obj, false)[name];}}
<!DOCTYPE HTML><html><head><meta charset="utf-8"><title></title><style>div{width:100px;height:50px;background:red;margin:10px;}</style> <script>window.onload=function (){var aDiv=document.getElementsByTagName('div');for(var i=0;i<aDiv.length;i++){aDiv[i].timer=null;//自訂屬性,加一個定時器aDiv[i].onmouseover=function (){startMove(this,400);};aDiv[i].onmouseout=function (){startMove(this,100);};}};var timer=null;function startMove(obj, iTarget){clearInterval(obj.timer);obj.timer=setInterval(function (){var speed=(iTarget-obj.offsetWidth)/6;speed=speed>0?Math.ceil(speed):Math.floor(speed);if(obj.offsetWidth==iTarget){clearInterval(obj.timer);}else{obj.style.width=obj.offsetWidth+speed+'px';}}, 30);}</script></head><body > <div ></div> <div ></div> <div ></div> </body></html>: