简单运动问题
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>简单运动</title> <style type="text/css"> #div1{ width: 200px; height: 200px; background-color: red; position: relative; left: -200px; top: 0; } #div1 span{ width: 20px; height: 50px; background-color:blue; position: absolute; left: 200px; top: 75px; } </style> <script type="text/javascript"> window.onload=function(){ var myDiv=document.getElementById('div1'); myDiv.onmouseover=function(){ startMove(0); } myDiv.onmouseout=function(){ startMove(-200); } } var timer=null; function startMove(iTarget){ clearInterval(timer); var myDiv=document.getElementById('div1'); timer=setInterval(function(){ var speed=0; speed=speed>0?Math.ceil(speed):Math.floor(speed); if (myDiv.offsetLeft>iTarget) { speed=-10; } else { speed=5; } if (myDiv.offsetLeft==iTarget) { clearInterval(timer); } else{ myDiv.style.left=myDiv.offsetLeft+speed+'px'; } },20); } </script> </head> <body> <div id="div1"> <span id="share">分享</span> </div> </body> </html>
为什么不是0和-200,总会多出来个8px,而且出来和退出的速度明显不一样呢。。。