I have a problem that I want to detect if an element is covered by another one in one page.
eg:
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/
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.
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?
To check if two elements overlap, use the getBoundingClientRect() method to get an object containing information about the relative position to the viewport of the elements. Then, compare the boundary edges (top, right, bottom, left) of the two rectangles. Here is the HTML for the examples in this article. Copied!
You can use the CSS position property in combination with the z-index property to overlay an individual div over another div element. The z-index property determines the stacking order for positioned elements (i.e. elements whose position value is one of absolute , fixed , or relative ).
Why not try the following :
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) Find the top element at position x, y:
topElt=document.elementFromPoint(x,y);
3) Check if the top element is the same than the original element :
if(elt.isSameNode(topElt)) console.log('no overlapping');
Are you looking for something like this?
http://jsfiddle.net/6v89b1fy/4/
var coverElem = $(".cover");
var elemArray = [];
elemArray.push($(".ele1"), $(".ele2"), $(".ele3"));
for(i=0; i< elemArray.length; i++)
{
var currElemOffset = elemArray[i].offset();
var currElemWidth = elemArray[i].width();
var currElemStPoint = currElemOffset.left ;
var currElemEndPoint = currElemStPoint + currElemWidth;
if(currElemStPoint <= coverElem.offset().left && coverElem.offset().left <= currElemEndPoint)
{
elemArray[i].append("<span>Covered</span>");
}
else
{
elemArray[i].append("<span>Not covered</span>");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With