首页 > 解决方案 > Find if element A is behind element B in HTML DOM tree

问题描述

Having an arbitrary pair of colliding elements (by rects) in DOM tree, how to find which one of them is in front and which one is behind?

Given el1 and el2 in DOM tree and knowing overlap points using el1.getBoundingClientRect() and el2.getBoundingClientRect() one can find the overlap rect. However having (x,y) point inside overlap rect document.elementFromPoint(x,y) returns just one element, which is in front of others at the given point. This element can be neither el1 nor el2.

So if one needs to find if el1 is in front of el2 or vice versa, this approach does not work.

标签: javascripthtmlcssdomz-index

解决方案


Use document.elementsFromPoint() (note the s), this will return an Array with all the elements that can be pointed to at these coordinates, ordered by z-index.

onclick = e => {
  console.log( document.elementsFromPoint( e.clientX, e.clientY ) );
}
.container div {
  width: 100px;
  height: 100px;
  border: 1px solid;
  position: absolute;
  opacity: 0.5;
}
.A {
  background: red;
  top: 0;
  left: 0;
}
.B {
  background: green;
  top: 50px;
  left: 50px;
}
.C {
  background: blue;
  top: 25px;
  left: 25px;
}
<div class="container">
  <div class="A"></div>
  <div class="B"></div>
  <div class="C"></div>
</div>

You can then filter this Array as you wish to make it contain only some elements and compare their position in that Array, though beware MS implementations return a NodeList, so you may need to reduce it to an Array first.


推荐阅读