HTML: Is there any way to determine if an element is behind another element?
We have an application with a search popup. You search for a term, and it finds them in the page and add a class to the word which in turn highlights the text. Occasionally the fo开发者_JAVA百科und instance is in an area of the page that is behind the search popup. If that is the case, I'd like tone the opacity down of the search popup so the user can see the instance behind it. Is there any simple way to do this? Any tips or tricks are appreciated. One requirement is that the search popup stay open after a search, so we can't just close/hide it.
You can use getBoundingClientRect()
on the found text and the popup and compare the dimensions.
MSDN
MDN range, element
You can act on text ranges directly, but it sounds like you have an element wrapping the found text in order to apply the highlight, so I'd just use that element. I think you can just pass your found text and your popup to this function to test if they overlap:
function isOverlapping (a, b)
{
var rectA = a.getBoundingClientRect();
var rectB = b.getBoundingClientRect();
return rectA.top < rectB.bottom && rectA.bottom > rectB.top &&
rectA.left < rectB.right && rectA.right > rectB.left;
}
Edit: I must have way too much time on my hands, because here's a fun little demo: http://jsfiddle.net/gilly3/qUFLJ/4/
Yes, using JavaScript it would be easy. Since you know if the popup is open, i assume that you know it's width and position. Just create a bounding box and check if your element is within this box. getBoundingClientRect is useful for this. If you're using jQuery, .offset can also help you.
Let me know if you need an example.
精彩评论