2012-08-22 164 views
35

我有兩個div元素。他們每個人都有450px的寬度和高度。如何檢查第一個div是否與第二個div重疊?如何檢查元素是否與其他元素重疊?

我試過使用javascript hittest,但它有點複雜。由於我試圖找出它是如何工作的,我想開始使用更簡單的代碼。

我發現我可以使用.getClientRects來獲取元素的邊界,但我不確定如何比較邊界。

請告訴我!

+2

http://stackoverflow.com/questions/4230029/jquery-javascript-collision-detection可以看到,如果這可以幫助你。 – user1071979

+0

所以你問的是,給定一組邊界矩形,你如何確定哪些重疊? – Blender

+0

@Blender //完全是 – Moon

回答

63

像這樣的rect1rect2通過getBoundingClientRect()檢索:

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

說明:如果在parenthese一個或多個表情true,沒有重疊。如果全部都是false,則必須有重疊。

+1

完美地工作...並且比谷歌上其他的測試功能更容易! – Moon

+0

剛剛發現這隻有在兩個元素都可見時纔有效 - 真遺憾! – graygilmore

+1

這真棒,我能夠用這個替換我的JQuery解決方案(涉及到需要抓住左側位置/高度並做數學運算),並且它提高了很多性能。 Thanks @Buu – Johannes

2

element.getBoundingClientRect()在現代瀏覽器中很安靜,它提供了相對於屏幕的邊界。看here比試驗,如果邊界框重疊,這是簡單的幾何圖形...

哦對不起......找到了你的編輯爲時已晚......

1

在Internet Explorer早於8版本,返回TextRectangle對象包含物理像素大小的座標,而從版本8開始,它包含邏輯像素大小的座標。

如果您需要整個元素的邊界矩形,請使用getBoundingClientRect方法。

12

這裏的東西我前幾天發了言: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)) 
    ); 
    } 
}; 
+1

裏面可以簡化爲:'rect1.top <= rect2.bottom && rect1.bottom> = rect2.top && rect1.left <= rect2.right && rect1.right> = rect2.left' –