//left1>left2 || right1>left2 //bottom1>top2
//如果第一个的右边大于第二个的左边 碰撞
//如果第二个的左边大于第二个的右边 过了,因此 left1<right2
//如果第一个的bottom大于第二个的top 则碰撞
//如果第一个的top大于第二个的bottom 则过了 top1<bottom2
这就是碰撞
拷贝此代码,放在本地运行一下吧
<html> <head> <style type="text/css"> *{margin:0px;padding:0px;} div{ width:100px; height:100px; background: #f30; } #div1{ position: absolute; } #div2{ position: absolute; left:330px; top:160px; } </style> <script type="text/javascript"> window.onload=function(){ var oDiv1=document.getElementById("div1"); var oDiv2=document.getElementById("div2"); //var num=10; oDiv1.onmousedown=function(ev){ var oEvent=ev||event; var mouseX=oEvent.clientX; var mouseY=oEvent.clientY; var diffx=mouseX-oDiv1.offsetLeft; var diffy=mouseY-oDiv1.offsetTop; document.onmousemove=function(ev){ var oEvent=ev||event; var oMouseX=oEvent.clientX; var oMouseY=oEvent.clientY; var ol=oMouseX-diffx; var ot=oMouseY-diffy; oDiv1.style.left=ol+"px"; oDiv1.style.top=ot+"px"; var res=pz(oDiv1,oDiv2); console.log(res); if(res){ oDiv2.style.backgroundColor="#06f"; } } document.onmouseup=function(){ document.onmousemove=null; document.onmouseup=null; } } //alert(Math.sqrt(num)); } function pz(obj1,obj2){ var left1=obj1.offsetLeft; var right1=obj1.offsetLeft+obj1.offsetWidth; var top1=obj1.offsetTop; var bottom1=obj1.offsetTop+obj1.offsetHeight; var left2=obj2.offsetLeft; var right2=obj2.offsetLeft+obj2.offsetWidth; var top2=obj2.offsetTop; var bottom2=obj2.offsetTop+obj2.offsetHeight; //left1>left2 || right1>left2 //bottom1>top2 //如果第一个的右边大于第二个的左边 碰撞 //如果第二个的左边大于第二个的右边 过了,因此 left1<right2 /** 如果第一个的bottom大于第二个的top 则碰撞 如果第一个的top大于第二个的bottom 则过了 top1<bottom2 **/ if((right1>left2 && left1<right2) && (bottom1>top2 && top1<bottom2)){ return true; }else{ return false; } } </script> </head> <body> <div id="div1">1</div> <div id="div2">2</div> </body> </html>