jQuery 如何检测两个div是否与jquery接触?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5419134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:08:27  来源:igfitidea点击:

How to detect if two divs touch with jquery?

jqueryhtml

提问by sudheer

I'm just developing a simple balloon game with two divs. The problem is that I'm unable to trigger a function when the two divs touch each other.

我只是在开发一个带有两个 div 的简单气球游戏。问题是当两个 div 相互接触时我无法触发功能。

回答by BC.

You're looking for bounding box collision detection. If you want to raise an event, you have to repeatedly test, but it would be better just to run the function over all your game objects from your game loop. The sandbox is at http://jsfiddle.net/nGRwt/7/

您正在寻找边界框碰撞检测。如果你想引发一个事件,你必须反复测试,但最好只是在游戏循环中的所有游戏对象上运行该函数。沙箱位于http://jsfiddle.net/nGRwt/7/

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

回答by eruciform

You can try jquery-collisionplus jquery-ui-draggable-collision. Full disclosure: I just wrote and released these on sourceforge.

您可以尝试jquery-collision加上jquery-ui-draggable-collision。完全披露:我刚刚在 sourceforge 上编写并发布了这些。

The first allows this:

第一个允许:

var hit_list = $("#collider").collision(".obstacle");

which is the list of all ".obstacle" that overlap "#collider".

这是与“#collider”重叠的所有“.obstacle”的列表。

The second allows:

第二个允许:

$("#collider").draggable( { obstacle: ".obstacle" } );

Which gives you (among other things), a "collision" event to bind to:

这给你(除其他外),一个“碰撞”事件绑定到:

$("#collider").bind( "collision", function(event,ui){...} );

And you can even set:

你甚至可以设置:

$("#collider").draggable( { obstacle: ".obstacle", preventCollision: true } );

to prevent "#collider" from ever overlapping any ".obstacle" while dragging.

防止“#collider”在拖动时与任何“.obstacle”重叠。

回答by Gaurav Mogha

in Native Javascript

在原生 Javascript 中

var is_colliding = function(div1, div2) {
  var d1_height = div1.offsetHeight;
  var d1_width = div1.offsetWidth;
  var d1_distance_from_top = div1.offsetTop + d1_height;
  var d1_distance_from_left = div1.offsetLeft + d1_width;

  var d2_height = div2.offsetHeight;
  var d2_width = div2.offsetWidth;
  var d2_distance_from_top = div2.offsetTop + d2_height;
  var d2_distance_from_left = div2.offsetLeft + d2_width;

  var not_colliding =
    d1_distance_from_top < div2.offsetTop ||
    div1.offsetTop > d2_distance_from_top ||
    d1_distance_from_left < div2.offsetTop ||
    div1.offsetLeft > d2_distance_from_left;

  return !not_colliding;
};

回答by SpacemanPete

The answer from Victor S above was useful but I needed to check whether two divs overlapped completely, i.e. eclipsed (but this was hard to google for since results were polluted with references to the Eclipse IDE).

上面来自 Victor S 的答案很有用,但我需要检查两个 div 是否完全重叠,即黯然失色(但这很难用谷歌搜索,因为结果被 Eclipse IDE 的引用污染了)。

Sharing my modified version in case anyone finds it useful:

分享我的修改版本,以防有人觉得它有用:

$(function() {
  /**
   * Function to determine whether the first element completely 
   *  eclipses the second element
   */
  function collision($div2, $div1) {
    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;

    return x1 > x2 && y1 > y2 && b1 < b2 && r1 < r2
      ? true
      : false
  }

  // draggable jQuery listener required jQuery UI
  // Just used to illustrate the above
  $('#div1,#div2').draggable({
    drag: function() {
      if (collision($('#div1'), $('#div2'))) {
        $('#div2').text('Eclipsing').css({'background-color': 'grey'})
      } else {
        $('#div2').text('Not eclipsing').css({'background-color': 'green'})
      }

      $('#result').text(collision($('#div1'), $('#div2')));

    }
  });
});
.box {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

#div1 {
  width: 200px;
  height: 200px;
  background-color: pink;
}
#div2 {
  width: 75px;
  height: 75px;
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>

<strong>Drag divs around.</strong>
<p>Eclipsing? <span id="result">false</span>

<div id="wrapper">
  <div id="div1" class="box">
    Div1
  </div><br/>
  <div id="div2" class="box">
    Not eclipsing
  </div>
</div>