<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>缓冲1</title> <style type="text/css"> #div1{height: 200px; width: 200px; background: blue; position: relative; left: -200px; } #div1 span{ position: absolute; height: 50px; width: 15px; left: 200px; top: 75px; background-color: red; } *{margin: 0;padding: 0;} </style> <script type="text/javascript"> window.onload=function () { var div1=document.getElementById('div1'); div1.onmouseover=function(){ startmove(0); } div1.onmouseout=function(){ startmove(-200); } } var timer=null; function startmove (itarget) { clearInterval(timer); timer=setInterval(function(){ var speed=(itarget-div1.offsetLeft)/20;//speed赋值后,下边接着判断 speed=speed>0?Math.ceil(speed):Math.floor(speed); if (itarget==div1.offsetLeft) { clearInterval(timer); } else{ div1.style.left=div1.offsetLeft+speed+'px'; }; },30) } </script> </head> <body> <div id="div1"> <span>分享</span> </div> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>缓冲2</title> <style type="text/css"> #div1{height: 200px; width: 200px; background: blue; position: relative; left: -200px; } #div1 span{ position: absolute; height: 50px; width: 15px; left: 200px; top: 75px; background-color: red; } *{margin: 0;padding: 0;} </style> <script type="text/javascript"> window.onload=function () { var div1=document.getElementById('div1'); div1.onmouseover=function(){ startmove(0); } div1.onmouseout=function(){ startmove(-200); } } var timer=null; function startmove (itarget) { clearInterval(timer); timer=setInterval(function(){//这里speed直接赋值并且判断 var speed=speed>0?Math.ceil((itarget-div1.offsetLeft)/20):Math.floor((itarget-div1.offsetLeft)/20); if (itarget==div1.offsetLeft) { clearInterval(timer); } else{ div1.style.left=div1.offsetLeft+speed+'px'; }; },30) } </script> </head> <body> <div id="div1"> <span>分享</span> </div> </body> </html>
两种speed的赋值方式,造成两种结果:第一段代码向右移动后的left值正常,能达到0;第二段代码向右移动后的left值是-19px.
echo_kinchao
忧郁的狮子座