2016-09-05 56 views
0

我試圖檢測我的兩個div是否重疊。 我有一個包含一段文字的div,div可以用buttonclick進行放大和縮小。 Underneth這是另一個將充滿「事物」的div,直到某個點它會變成一個滾動列表。現在到棘手的部分。如何檢查兩個div是否重疊?

這項工作做得很好,直到得到填補到最大(我不能改變)列表或在平板電腦7" 。

所以蔭嘗試寫,如果兩個div重疊可以檢測的方法。 我不能找到這個隨地一個很好的解決方案,瑪貝有沒有或瑪貝我不是在正確的事情搜索,無論哪種方式,我需要幫助

這是我到目前爲止已經試過:

 crashDetection(event, pageInfoBlock) { 
      let helBlockTop = parseInt(document.getElementById('page-info').getBoundingClientRect().bottom, 10); 
      let helBlockBottom = parseInt(document.getElementById('page-info').getBoundingClientRect().height, 10); 
      let containerBottom = parseInt(document.getElementById('bottomContainer').getBoundingClientRect().top, 10); 

      if (helBlockTop + helBlockBottom > containerBottom && containerBottom !== 0) { 
console.log("It overlap"); 
      } 
     } 

該作品幾乎是因爲在某些情況下,我滾動包含整個事情的div得到伸展,所以它看起來不錯..但如果我再次滾動到頂部他們重疊..和我的方法檢測重疊,即使沒有..

所以我的問題如何檢測兩個div是否重疊? 沒有jQuery,請和遺憾,我的英文不好..:P

+0

沒有讓你的DOM結構的初步認識部分(即兩個'divs'是否兄弟姐妹,子女,或更復雜的東西,和你的代碼中的id與什麼相匹配,很難猜測發生了什麼事情,並且提供你的CSS的相關部分來理解你的div重疊的方式/原因可能會有所幫助,它可能更容易直接修復你的CSS嘗試解決是在JS之後。 – jcaron

+0

[jQuery/JavaScript碰撞檢測](http://stackoverflow.com/questions/4230029/jquery-javascript-collision-detection)或http://stackoverflow.com/問題/ 11641638 /檢測-id-html-element-is-overlapping-another-html-element – Pete

+1

Im很抱歉,我盯着這個問題,因爲我發現了一個像魅力一樣的awnser:http://stackoverflow.com/questions/12066870/how-to-check-if-an-element-is-overlapping-其他元素 感謝您的幫助! – user3727466

回答

0
function collision($div1, $div2) { 
      var x1 = $div1.offset().left; 
      var y1 = $div1.offset().top; 
      var h1 = $div1.outerHeight(true); 
      var w1 = $div1.outerWidth(true); 
      var b1 = y1 + h1; 
      var r1 = x1 + w1; 
      var x2 = $div2.offset().left; 
      var y2 = $div2.offset().top; 
      var h2 = $div2.outerHeight(true); 
      var w2 = $div2.outerWidth(true); 
      var b2 = y2 + h2; 
      var r2 = x2 + w2; 
      if (b1 <= y2 || y1 >= b2 || r1 <= x2 || x1 >= r2) return false; 
      return true; 
     } 
+0

有沒有理由不使用邊界矩形('getBoundingClientRect')? –

+0

如果我們需要一些像1px一樣大小的協商,diff會協商,所以我們可以在這裏進行管理。到任何一個div –