检查特定 div 之间的碰撞。

9

如何检查特定div之间的碰撞?

目前我正在使用getBoundingClientRect(),但它会检查每个div:

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

我该如何检查特定的内容?使用这个 for 循环,我可以获取我想要检查的 div 的 ID:

for (var x = 1; x <= noOfBoxArt; x++) {
    console.log('#boxArt' + x);
}

可能重复出现的问题:https://dev59.com/O2855IYBdhLWcg3woV_M,http://stackoverflow.com/q/8829421/1048572 - Bergi
谢谢,我会看一下它们。它们使用jQuery UI droppable进行碰撞检测。我想要检测一个div是否已经被放置在同一个位置。 - Joey Morani
3个回答

10

好的,最终我使用了一个修改过的这个重复问题的版本。完成工作的函数是:

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

使用 overlaps( div1, div2 ); 对两个元素进行检测(返回 true 或 false)。


7

你也可以使用广泛支持的getBoundingClientRect()来实现此操作。

这是我使用以下教程开发的函数:

2D 碰撞检测

// a & b are HTMLElements
function overlaps(a, b) {
  const rect1 = a.getBoundingClientRect();
  const rect2 = b.getBoundingClientRect();
  const isInHoriztonalBounds =
    rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x;
  const isInVerticalBounds =
    rect1.y < rect2.y + rect2.height && rect1.y + rect1.height > rect2.y;
  const isOverlapping = isInHoriztonalBounds && isInVerticalBounds;
  return isOverlapping;
}

1

纯JavaScript版本

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接