2009-10-13 43 views
7

實施例:有效地檢測當同級元素重疊

<div id="big">&nbsp;</div> 
<div class="small">&nbsp;</div> 
<div class="small">&nbsp;</div> 
<div class="small">&nbsp;</div> 
<div class="small">&nbsp;</div> 
<div class="small">&nbsp;</div> 
<!-- ...and so on --> 

「#big」絕對定位的「小」 s的部分的後面,但 不是父元素。

我一直在做這樣的:

  var smallArray = []; 

      var $big = $('#big'); 
      var $bigPos = $big.offset(); 

      $('div.small').each(function() { 
        var $this = $(this); 
        var $thisPos = $this.offset(); 

        if(
          $thisPos.left >= $bigPos.left && 
          $thisPos.left <= $bigPos.left+$big.outerWidth() && 
          $thisPos.top >= $bigPos.top && 
          $thisPos.top <= $bigPos.top+$big.outerHeight() 
        ) smallArray.push($this); 
      }); 

...但這似乎缺憾。我是否錯過了jQuery 或vanilla JavaScript的某些方法,這將允許我以更優雅的 &高效方式執行此操作?

感謝您提供的任何幫助。

+0

你想完成什麼? – 2009-10-13 19:23:53

+0

您的公式只會檢測一個小元素的左上角點是否在大元素內。如果小的右下角位於大的內部會發生什麼?它們重疊,但是你的公式不會檢測到它。 – cmcculloh 2010-02-05 19:16:42

回答

21

如果任何指定的元件中的重疊的目標元素此公式將檢測:

function findIntersectors(targetSelector, intersectorsSelector) { 
    var intersectors = []; 

    var $target = $(targetSelector); 
    var tAxis = $target.offset(); 
    var t_x = [tAxis.left, tAxis.left + $target.outerWidth()]; 
    var t_y = [tAxis.top, tAxis.top + $target.outerHeight()]; 

    $(intersectorsSelector).each(function() { 
      var $this = $(this); 
      var thisPos = $this.offset(); 
      var i_x = [thisPos.left, thisPos.left + $this.outerWidth()] 
      var i_y = [thisPos.top, thisPos.top + $this.outerHeight()]; 

      if (t_x[0] < i_x[1] && t_x[1] > i_x[0] && 
       t_y[0] < i_y[1] && t_y[1] > i_y[0]) { 
       intersectors.push($this); 
      } 

    }); 
    return intersectors; 
} 

Here is a POC.

This SO question是解決這個問題非常有幫助。

+0

我還需要在jQuery中檢測重疊元素,並且一直使用「jquery-overlapping」插件,但它有時會使IE崩潰。這個功能是一個很好的替代品。謝謝! – shipshape 2010-03-16 21:36:04

+0

嘿@shipshape如果jQuery Overlaps崩潰IE,爲什麼你沒有在github上報告?會幫助很多其他用戶... – bart 2011-09-10 01:22:30

+0

@cmcculloh感謝分享! – 2012-04-05 18:54:23