Detecting whether two divs overlap [duplicate]

我的梦境 提交于 2019-12-01 18:08:49

问题


Possible Duplicate:
How to detect if two divs touch with 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:

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

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


回答1:


There is already a query here having an answer : How to detect if two divs touch with 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;
    }



回答2:


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



来源:https://stackoverflow.com/questions/14012766/detecting-whether-two-divs-overlap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!