如何检测元素是否被另一个元素覆盖/重叠? [英] How to detect if an element is covered/overlapped by another one?

查看:78
本文介绍了如何检测元素是否被另一个元素覆盖/重叠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我想检测一个元素是否被一个页面中的另一个元素覆盖。

I have a problem that I want to detect if an element is covered by another one in one page.

例如:

DOM elements
<div class="ele ele1"><p>A</p></div>
<div class="ele ele2"><p>B</p></div>
<div class="ele ele3"><p>C</p></div>
<div class="cover"><p>D</p></div>


CSS style
.ele{
   display: inline-block;
   width: 100px;
   height: 100px;
   position: relative;
}
p{   
  width: 100%;
  text-align: center;
}
.ele1{
  background-color: red;
}
.ele2{
  background-color: blue;
}
.ele3{
  background-color: green;
}
.cover{
   position: absolute;
   width: 100px;
   height: 100px;
   left: 300px;
   top: 10px;
   background: grey;
}

http://jsfiddle.net/veraWei/6v89b1fy/

如何检测元素A未被覆盖但元素C由ele D覆盖?
还有一件事:D的数量是不确定的。也许页面上有E / F / G ......
我感谢所有的想法或现有的例子/ jQuery插件/ CSS /等。

How to detect element A is not been covered but element C is covered by ele D? One more thing: the number of "D" is uncertain. Maybe there are E/F/G... in the page. I appreciate all the thoughts or existing examples/jQuery plugins/CSS/etc.

感谢所有人的详细解答。但是我需要更多简短的解释可能是一个属性,表明A没有被任何元素覆盖,C被渲染覆盖。是否存在任何插件或属性?

Thanks all your guys' detailed answers. But I need more shortly explanation maybe one attribute that indicate that A is not covered by any elements and C is covered by rendering. Is there any plugin or attribute existing?

推荐答案

为什么不尝试以下操作:

Why not try the following :

1)找到相对于视口的元素位置:

1) Find the element position relative to the viewport:

rect=elt.getBoundingClientRect();
x=rect.left;
y=rect.top;

(或者可以考虑中点坐标)

(or may be consider the midpoints coordinates)

2)找到位置x,y的顶部元素:

2) Find the top element at position x, y:

topElt=document.elementFromPoint(x,y);

3)检查top元素是否与原始元素相同:

3) Check if the top element is the same than the original element :

if(elt.isSameNode(topElt)) console.log('no overlapping');

这篇关于如何检测元素是否被另一个元素覆盖/重叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆