碰撞检测:
function collTest(obj1,obj2){//由于if判断条件是对称的,obj1,obj2谁在前无所谓
//用于获取四条边的相对距离
var l1=obj1.offsetLeft;
var r1=obj1.offsetLeft+obj1.offsetWidth;
var t1=obj1.offsetTop;
var b1=obj1.offsetTop+obj1.offsetHeight;
var l2=obj2.offsetLeft;
var r2=obj2.offsetLeft+obj2.offsetWidth;
var t2=obj2.offsetTop;
var b2=obj2.offsetTop+obj2.offsetHeight;
if(r1>l2&&b1>t2&&l1<r2&&t1<b2){//发生碰撞,返回true
return true;
}else{return false;}
}
window.onload=function(){
var oBox1=document.getElementById("box1");
var oBox2=document.getElementById("box2");
oBox1.onmousedown=function(ev){
var e=ev||event;
var disX=e.clientX-oBox1.offsetLeft;
var disY=e.clientY-oBox1.offsetTop;
document.onmousemove=function(ev){
var e=ev||event;
var l=e.clientX-disX;
var t=e.clientY-disY;
oBox1.style.left=l+'px';
oBox1.style.top=t+'px';
if(collTest(oBox1,oBox2)){
oBox2.style.background="yellow";
}else{oBox2.style.background="green";}
}
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
oBox1.releaseCapture&&oBox1.releaseCapture();
}
oBox1.setCapture&&oBox1.setCapture();
return false;
}
}