javascript 检测两个div是否重叠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14012766/
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-10-26 20:28:47  来源:igfitidea点击:

Detecting whether two divs overlap

javascriptjqueryhtmlcollisiongamequery

提问by Johannes Flood

Possible Duplicate:
How to detect if two divs touch with jquery?

可能的重复:
如何检测两个 div 是否与 jquery 接触?

I've spent a lot of time trying to figure out how to detect if two divs are overlapping.
I tried the gamequery plugin and used it like this:

我花了很多时间试图弄清楚如何检测两个 div 是否重叠。
我尝试了 gamequery 插件并像这样使用它:

$("#" + checkform).collision("#" + checkform + "w").each(function(){
    alert("Collision");
});

Would you use the gamequery plugin and/or how would you do it?

你会使用 gamequery 插件和/或你会怎么做?

采纳答案by Amar

There is already a query here having an answer : How to detect if two divs touch with jquery?

这里已经有一个查询有答案:如何检测两个 div 是否与 jquery 接触?

For reference I copy the code here:

作为参考,我在这里复制代码:

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 Niet the Dark Absol

Use getBoundingClientRect()on each element, and see if they overlap that way. No jQuery needed.

getBoundingClientRect()在每个元素上使用,看看它们是否重叠。不需要jQuery。