如何检查一个元素是否与其他元素重叠?

我有两个 div 元素。它们每个都有450px 的宽度和高度。如何检查第一个 div 是否与第二个 div 重叠?

我尝试过使用 javascript hittest,但是它有点复杂。因为我正试图找出它实际上是如何工作的,所以我想从一个更简单的代码开始。

我发现我可以使用 。 getClientRects来获得一个元素的边界,但是我不确定如何比较边界。

请告诉我!

89484 次浏览

element.getBoundingClientRect() is quiet good in modern browsers, delivers a bounding relative to the screen. look here Than test if the bounding boxes overlap, that is simple geometry...

oh excuse me... found your edit too late...

In Internet Explorer earlier than version 8, the returned TextRectangle object contains the coordinates in physical pixel size, while from version 8, it contains the coordinates in logical pixel size.

If you need the bounding rectangle of the entire element, use the getBoundingClientRect method.

Something like this for rect1 and rect2 retrieved via getBoundingClientRect():

var overlap = !(rect1.right < rect2.left ||
rect1.left > rect2.right ||
rect1.bottom < rect2.top ||
rect1.top > rect2.bottom)

Explain: if one or more expressions in the parenthese are true, there's no overlapping. If all are false, there must be an overlapping.

Here's something I made some days ago: https://gist.github.com/yckart/7177551

var AABB = {
collide: function (el1, el2) {
var rect1 = el1.getBoundingClientRect();
var rect2 = el2.getBoundingClientRect();


return !(
rect1.top > rect2.bottom ||
rect1.right < rect2.left ||
rect1.bottom < rect2.top ||
rect1.left > rect2.right
);
},


inside: function (el1, el2) {
var rect1 = el1.getBoundingClientRect();
var rect2 = el2.getBoundingClientRect();


return (
((rect2.top <= rect1.top) && (rect1.top <= rect2.bottom)) &&
((rect2.top <= rect1.bottom) && (rect1.bottom <= rect2.bottom)) &&
((rect2.left <= rect1.left) && (rect1.left <= rect2.right)) &&
((rect2.left <= rect1.right) && (rect1.right <= rect2.right))
);
}
};