Efficiently Detect When Sibling Elements Overlap

后端 未结 1 1842
夕颜
夕颜 2020-12-01 10:11

Example:

 
 
 
<
相关标签:
1条回答
  • 2020-12-01 10:24

    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.

    0 讨论(0)
提交回复
热议问题