移动端碰撞检测
function drag(obj1,obj2,success){
obj1.addEventListener("touchstart", function(e) {
var touches = e.touches[0];
window.disX= touches.clientX - obj1.offsetLeft;
window.disX= touches.clientY - obj1.offsetTop;
//阻止页面的滑动默认事件
document.addEventListener("touchmove",defaultEvent,false);
},false)
obj1.addEventListener("touchmove", function(e) {
var touches = e.touches[0];
var oLeft = touches.clientX - disX;
var oTop = touches.clientY - disX;
if(oLeft < 0) {
oLeft = 0;
}else if(oLeft > document.documentElement.clientWidth - obj1.offsetWidth) {
oLeft = (document.documentElement.clientWidth - obj1.offsetWidth);
}
if(oTop < 0) {
oTop = 0;
}else if(oLeft > document.documentElement.clientHeight - obj1.offsetHeight) {
oTop = (document.documentElement.clientHeight - obj1.offsetHeight);
}
obj1.style.left = oLeft + "px";
obj1.style.top = oTop + "px";
},false);
obj1.addEventListener("touchend",function() {
document.removeEventListener("touchmove",defaultEvent,false);
var l1=obj1.offsetLeft;
var r1=l1+obj1.offsetWidth;
var t1=obj1.offsetTop;
var b1=t1+obj1.offsetHeight;
var l2=obj2.offsetLeft;
var r2=l2+obj2.offsetWidth;
var t2=obj2.offsetTop;
var b2=t2+obj2.offsetHeight;
if (l2>r1 || l1>r2 || t1>b2 || t2>b1){
obj2.style.background=‘green‘;
}
else{
success&&success()
}
},false);
function defaultEvent(e) {
e.preventDefault();
}
}
pc版本
window.onload=function (){
var oDiv1=document.getElementById(‘div1‘);
var oDiv2=document.getElementById(‘div2‘);
function drag(obj1,obj2,success){
obj1.onmousedown=function (ev){
var oEvent=ev || event;
var disX=oEvent.clientX-obj1.offsetLeft;
var disY=oEvent.clientY-obj1.offsetTop;
document.onmousemove=function (ev){
var oEvent=ev || event;
var left=oEvent.clientX-disX;
var top=oEvent.clientY-disY;
obj1.style.left=left+‘px‘;
obj1.style.top=top+‘px‘;
var l1=obj1.offsetLeft;
var r1=l1+obj1.offsetWidth;
var t1=obj1.offsetTop;
var b1=t1+obj1.offsetHeight;
var l2=obj2.offsetLeft;
var r2=l2+obj2.offsetWidth;
var t2=obj2.offsetTop;
var b2=t2+obj2.offsetHeight;
if (l2>r1 || l1>r2 || t1>b2 || t2>b1){
obj2.style.background=‘green‘;
}
else{
success()
}
};
document.onmouseup=function (){
document.onmousemove=null;
document.onmouseup=null;
};
return false;
};
}
drag(oDiv1,oDiv2,function(){
oDiv2.style.background="yellow"
})
};