如果我有一个元素的4个角的x和y位置,我怎么知道元素A是否在元素B中

时间:2014-07-01 22:46:58

标签: javascript geometry bounds

我的代码(正确)获得了4个角落的x和y位置。我想知道元素A是否完全在元素B的范围内(即使是1px)。我不能为我的生活找到正确的方程式。

我有这个,但只有 检查A的左上角是否在B内。

xIntersects = a.topLeft.x >= b.topLeft.x && a.topLeft.x <= b.topRight.x;
yIntersects = a.topLeft.y >= b.topLeft.y && a.topLeft.y <= b.bottomLeft.y;

console.log(xIntersects && yIntersects) // true only when topLeft of A is in B

我可以为四个角中的每个角写一个这样的声明,但这看起来真的很贵,并且可能有更好的处理方法。

我的代码在JS中,但这个答案实际上可以是任何语言。

1 个答案:

答案 0 :(得分:0)

结束使用

  function intersects (el1, el2) {
    var a = el1.getCoordinates();
    var b = el2.getCoordinates();
    return   (a.left <= b.right &&
              b.left <= a.right &&
              a.top <= b.bottom &&
              b.top <= a.bottom)
  }

如果您使用MooTools,则getCoordinates将返回顶部,左侧,底部和右侧。如果不是,你需要手动解决这个问题。