Check for collision between specific divs?

Does anyone know how to check for collisions between certain divs? getBoundingClientRect() now I'm using getBoundingClientRect() , but it checks every div:

 if (this.getBoundingClientRect()) { animateContinue = 1; } 

How can I check specific? Using this for loop, I can get the identifiers of the sections I want to check.

 for (var x = 1; x <= noOfBoxArt; x++) { console.log('#boxArt'+x); } 
+5
source share
2 answers

Good. Ended up using a modified version of this duplicate . Function performing the work:

 var overlaps = (function () { function getPositions( elem ) { var pos, width, height; pos = $( elem ).position(); width = $( elem ).width() / 2; height = $( elem ).height(); return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ]; } function comparePositions( p1, p2 ) { var r1, r2; r1 = p1[0] < p2[0] ? p1 : p2; r2 = p1[0] < p2[0] ? p2 : p1; return r1[1] > r2[0] || r1[0] === r2[0]; } return function ( a, b ) { var pos1 = getPositions( a ), pos2 = getPositions( b ); return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] ); }; })(); 

and called using overlaps( div1, div2 ); (returns true or false).

+8
source

Pure version of JS

 var overlaps = (function () { function getPositions( elem ) { var width = parseFloat(getComputedStyle(elem, null).width.replace("px", "")); var height = parseFloat(getComputedStyle(elem, null).height.replace("px", "")); return [ [ elem.offsetLeft, elem.offsetLeft + width ], [ elem.offsetTop, elem.offsetTop + height ] ]; } function comparePositions( p1, p2 ) { var r1 = p1[0] < p2[0] ? p1 : p2; var r2 = p1[0] < p2[0] ? p2 : p1; return r1[1] > r2[0] || r1[0] === r2[0]; } return function ( a, b ) { var pos1 = getPositions( a ), pos2 = getPositions( b ); return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] ); }; })(); 
0
source

Source: https://habr.com/ru/post/1402207/


All Articles