Mobile-side collision detection
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;
Block sliding default events for pages
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.documentelemen T.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 version
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"
})
};
About mobile drag-and-drop