javascript - 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.
解决方案
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.
推荐阅读
- matlab - 如何从 Simulnik Thermal House 示例中加载数据?
- django - 不使用模板仅使用视图文件将数据发布到数据库中
- java - 本地存储库中存在依赖关系,但远程存储库中的 Maven 搜索
- python - 是否有一个 python (3) 本机等效于使用 rlwrap 调用脚本?
- excel - 从过滤范围复制单元格,其中只有一行
- ejb - 在 @Stateful 的情况下,EJB 容器如何区分一个客户端和另一个客户端
- html - 如何为html中的特定行实现滚动条
- html - Angular - 仅在值匹配时修补选择下拉列表中的选定值
- html - 隐藏/删除 DIV 中的特定文本
- php - 通过 htacess 从 Codeigniter 中的 URL 中删除主文件夹名称