简体   繁体   中英

How to programmatically tell if two absolutely positioned elements overlap?

I don't think there's any such method in the DOM API like element.doesOverlap(otherElement) , so I think I have to calculate this by hand, right? Not sure if there are any shortcuts.

If not, what is the method for this? It seems like there's so many ways something could overlap....it would be so many conditionals. Is there a concise way of writing this?

In pseudo code, I have this:

if (
  ((A.top < B.bottom && A.top >= B.top)
    || (A.bottom > B.top && A.bottom <= B.bottom))

    &&

    ((A.left < B.right && A.left >= B.left)
    || (A.right > B.left && A.right <= B.right))) {
  // elements A and B do overlap
}

^Is this the simplest way?

This is essentially and x,y comparison problem. You essentially need to compare the two element by there x,y positions at all boundaries ( top, right, bottom and left ) if they overlap anywhere.

A simple method would be, to test that they don't overlap.

Two items could be considered to overlap if none of the following are true:

 - box1.right < box2.left // too far left
 - box1.left > box2.right // too far right
 - box1.bottom < box2.top // too far above
 - box1.top > box2.bottom // too far below

Only really a slight change to what you had.

 function checkOverlap(elm1, elm2) { e1 = elm1.getBoundingClientRect(); e2 = elm2.getBoundingClientRect(); return e1.x <= e2.x && e2.x < e1.x + e1.width && e1.y <= e2.y && e2.y < e1.y + e1.height; } window.onload = function() { var a = document.getElementById('a'); var b = document.getElementById('b'); var c = document.getElementById('c'); console.log("a & b: "+checkOverlap(a,b)); console.log("a & c: "+checkOverlap(a,c)); console.log("b & c: "+checkOverlap(b,c)); }
 <div id="a" style="width:120px;height:120px;background:rgba(12,21,12,0.5)">a</div> <div id="b" style="position:relative;top:-30px;width:120px;height:120px;background:rgba(121,211,121,0.5)">b</div> <div id="c" style="position:relative;top:-240px;left:120px;width:120px;height:120px;background:rgba(211,211,121,0.5)">c</div>

There isn't an easier way. The correct code is this, covering all possible ways two elements can overlap:

const doElementsOverlap = (elementA: any, elementB: any) => {
  const A = elementA.getBoundingClientRect();
  const B = elementB.getBoundingClientRect();
  return (
    ((A.top < B.bottom && A.top >= B.top)
    || (A.bottom > B.top && A.bottom <= B.bottom)
    || (A.bottom >= B.bottom && A.top <= B.top))

    &&

    ((A.left < B.right && A.left >= B.left)
    || (A.right > B.left && A.right <= B.right)
    || (A.left < B.left && A.right > B.right))
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM