1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <style> 5 #div1 {100px; height:200px; background:#CCC; position:absolute; left:-100px;} 6 #div1 span {20px; height:60px; line-height:20px; text-align:center; left:100px; top:70px; background:yellow; position:absolute;} 7 8 </style> 9 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 10 <title>无标题文档</title> 11 <script type="text/javascript"> 12 window.onload=function () 13 { 14 var oDiv=document.getElementById('div1'); 15 16 oDiv.onmouseover=function () 17 { 18 //函数调用 19 startMove(0); 20 } 21 22 oDiv.onmouseout=function () 23 { 24 //函数调用 25 startMove(-100); 26 } 27 } 28 var timer=null; 29 30 function startMove(iTarget) 31 { 32 var oDiv=document.getElementById('div1'); 33 34 clearInterval(timer); 35 timer=setInterval(function (){ 36 //缓冲运动的实现 37 var iSpeed=(iTarget-oDiv.offsetLeft)/8; 38 39 iSpeed = iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed); 40 41 if(oDiv.offsetLeft==iTarget) 42 { 43 clearInterval(timer); 44 } 45 else 46 { 47 oDiv.style.left=oDiv.offsetLeft+iSpeed+'px'; 48 } 49 }, 30); 50 } 51 </script> 52 </head> 53 54 <body> 55 <div id="div1"> 56 <span>分享到</span> 57 </div> 58 </body> 59 </html>
注:在发现有大量函数代码重复的时候,可以考虑使用参数,节省代码的空间。同时注意,在写css样式的时候对于运动来说一定要使用定位。
缓冲运动中一定要注意函数的取整。