<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> *{ padding: 0; margin: 0; } .a{ width: 100px; height: 100px; background: aquamarine; margin-bottom: 10px; } </style> <script type="text/javascript"> var timer; window.onload=function(){ var div1=document.getElementById("div1"); var div2=document.getElementById("div2"); div1.onmouseover=function(){ startMove(this,"height",300); } div1.onmouseout=function(){ startMove(this,"height",100);console.log("hello"); } } function startMove(obj,attr,iTarget){ clearInterval(timer); var icur=parseInt(getStyle(obj,attr)); timer=setInterval(function(){ speed=(iTarget-icur)/5; speed=speed>0?Math.ceil(speed):Math.floor(speed); if(icur==iTarget){ clearInterval(timer); } else{ obj.style[attr]=icur+speed+'px';console.log("hello"); } },50); } function getStyle(obj,attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; } else{ return getComputedStyle(obj,false)[attr]; } } </script> </head> <body> <div id="div1" class="a"></div> <div id="div2" class="a"></div> </body> </html>
var timer; window.onload = function(){ var div1 = document.getElementById("div1"); var div2 = document.getElementById("div2"); div1.onmouseover = function(){ startMove(this,"height",300); } div1.onmouseout = function(){ startMove(this,"height",100); } } function startMove(obj,attr,iTarget){ clearInterval(timer); timer = setInterval(function(){ var icur = parseInt(getStyle(obj,attr)); var speed = (iTarget - icur) / 5; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if(icur==iTarget){ clearInterval(timer); } else{ obj.style[attr] = icur + speed + 'px'; } },50); } function getStyle(obj,attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; } else{ return getComputedStyle(obj,false)[attr]; } }
var icur = parseInt(getStyle(obj,attr)); 这句写在setInterval 里面 否则定时器不能每次获得新的属性值