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 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>js-碰撞运动</title> 6 <style type="text/css"> 7 * { padding: 0; margin: 0; } 8 ul,li{ list-style:none} 9 .box{ width:100px; height:100px; background:#FF0000 ; position:absolute; top:100px; left:100px} 10 </style> 11 12 <script type="text/javascript"> 13 14 window.onload=function(){ 15 16 var speedX=0,speedY=0; 17 var lastX=0,lastY=0; 18 var timer=null; 19 var obj=document.getElementById("box"); 20 21 obj.onmousedown=function(e){ 22 var e=e||window.event; 23 var disX=e.clientX-obj.offsetLeft; 24 var disY=e.clientY-obj.offsetTop; 25 document.onmousemove=function(e){ 26 clearInterval(timer); 27 var e=e||window.event; 28 var l=e.clientX-disX; 29 var t=e.clientY-disY; 30 obj.style.left=l+"px"; 31 obj.style.top=t+"px"; 32 speedX=l-lastX; 33 speedY=t-lastY; 34 lastX=l; 35 lastY=t; 36 37 } 38 39 document.onmouseup=function(){ 40 41 document.onmousemove=null; 42 document.onmouseup=null; 43 objMove(); 44 45 return false; 46 47 } 48 49 return false; 50 51 } 52 53 54 function objMove(){ 55 56 57 timer=setInterval(function(){ 58 59 speedY+=5; 60 61 var l=obj.offsetLeft+speedX; 62 var t=obj.offsetTop+speedY; 63 64 if(t>=document.documentElement.clientHeight-obj.offsetHeight){ 65 t=document.documentElement.clientHeight-obj.offsetHeight; 66 67 speedY*=-0.8; 68 speedX*=0.8; 69 } 70 if(t<=0){ 71 t=0; 72 speedY*=-1; 73 speedX*=0.8; 74 75 } 76 if(l>=document.documentElement.clientWidth-obj.offsetWidth){ 77 l=document.documentElement.clientWidth-obj.offsetWidth; 78 speedX*=-0.8; 79 80 } 81 if(l<=0){ 82 83 l=0; 84 speedX*=-0.8; 85 86 } 87 if(Math.abs(speedX)<1){ 88 89 speedX=0; 90 91 } 92 if(Math.abs(speedY)<1){ 93 94 speedY=0; 95 96 } 97 if(speedX==0&&speedY==0&& t==document.documentElement.clientHeight-obj.offsetHeight){ 98 99 clearInterval(timer); 100 101 102 } 103 104 obj.style.left=l+"px"; 105 obj.style.top=t+"px"; 106 107 },30); 108 109 110 } 111 112 113 114 115 } 116 117 118 119 </script> 120 </head> 121 <body> 122 <div class="box" id="box"></div> 123 </body> 124 </html>