Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

jquery - Efficiently Detect When Sibling Elements Overlap

Example:

<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" is positioned absolutely behind a portion of the ".small"s, but is not a parent element.

I have been doing this:

           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);
            });

...but this seems kludgy. Am I missing out on some methods of jQuery or vanilla JavaScript that will allow me to do this in a more elegant & efficient manner?

Thanks ahead for any help you can provide.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This formula will detect if any of the specified elements is overlapping a target element:

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 was very helpful in solving this problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...