JS-Collision Detection and Collision Detection
A simple Collision Detection example is used to check whether div1 is in conflict with div2. When div1 encounters div2, it changes the color of div2.
Take a look at the analysis diagram:
When div1 is active in a region above div2 (t2 ),
When div1 is active in the right line (r2) of div2 in the right area
When div1 is active in a region below div2 (b2 ),
When div1 is active in the left-side (r2) area of div2
In addition to the above four situations, other situations indicate that div1 and div2 have met, and the next interview will complete the test code
<div id="div1"></div><div id="div2"></div>
<style> #div1{ width:100px ;height: 100px;background: green; position: absolute; } #div2{ width:100px ;height: 100px;background: yellow; position: absolute;left: 300px;top: 200px;z-index: -1; }</style>
<Script> window. onload = function () {var oDiv = document. getElementById ('div1 '); var oDiv2 = document. getElementById ('div2'); var disX = 0; var disY = 0; oDiv. onmousedown = function (ev) {var ev = ev | window. event; disX = ev. clientX-oDiv. offsetLeft; disY = ev. clientY-oDiv. offsetTop; document. onmousemove = function (ev) {var ev = ev | window. event; var t1 = oDiv. offsetTop; var l1 = oDiv. offsetLeft; var r1 = oDiv. offsetLeft + oDiv. offsetWidth; var b1 = oDiv. offsetTop + oDiv. offsetHeight; var t2 = oDiv2.offsetTop; var l2 = oDiv2.offsetLeft; var r2 = oDiv2.offsetLeft + oDiv2.offsetWidth; var b2 = oDiv2.offsetTop + oDiv2.offsetHeight; if (b1 <t2 | l1> r2 | t1> b2 | r1 <l2) {// indicates not met} else {oDiv2.style. background = 'blue';} oDiv. style. left = ev. clientX-disX + 'px '; oDiv. style. top = ev. clientY-disY + 'px';} document. onmouseup = function () {document. onmousemove = null; document. onmouseup = null;} return false; }}</script>