Check collision between certain divs

前端 未结 3 1514
无人及你
无人及你 2021-01-05 04:42

How can I check for collision between certain divs?

At the moment I\'m using getBoundingClientRect(), but it checks for every div:

if (thi         


        
3条回答
  •  失恋的感觉
    2021-01-05 05:38

    Pure JavaScript version

    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] );
        };
    })();
    

提交回复
热议问题