检查元素是否在DOM中可见 [英] Check if element is visible in DOM

查看:99
本文介绍了检查元素是否在DOM中可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么方法可以检查一个元素是否可以在纯JS(没有jQuery)中可见?

Is there any way that I can check if an element is visible in pure JS (no jQuery) ?

所以,例如,在这个页面中:性能自行车,如果您悬停在交易(在顶级菜单上),会出现一个交易窗口,但一开始没有显示出来。它是在HTML中,但它不可见。

So, for example, in this page: Performance Bikes, if you hover over Deals (on the top menu), a window of deals appear, but at the beginning it was not shown. It is in the HTML but it is not visible.

所以,给定一个DOM元素,我如何检查它是否可见?我试过: window.getComputedStyle(my_element)['display']); 但似乎没有工作。我想知道我应该检查哪些属性。我想到:

So, given a DOM element, how can I check if it is visible or not? I tried: window.getComputedStyle(my_element)['display']); but it doesn't seem to be working. I wonder which attributes should I check. It comes to my mind:

display !== 'none'
visibility !== 'hidden'

我可能会缺少的任何其他人

Any others that I might be missing?

推荐答案

根据此MDN文档,一个元素的offsetParent属性将通过显示样式属性隐藏或返回null。只要确保元素不固定。一个脚本检查这个,如果你的页面上没有position:fixed;元素,可能如下所示:

According to this MDN documentation, an element's offsetParent property will return null whenever it, or any of its parents, is hidden via the display style property. Just make sure that the element isn't fixed. A script to check this, if you have no 'position:fixed;' elements on your page, might look like:

//Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    return (el.offsetParent === null)
}

另一方面,如果您具有可能在此搜索中被捕获的固定元素,你会悲伤地(慢慢地)使用 window.getComputedStyle()。在这种情况下的功能可能是:

On the other hand, if you do have position fixed elements that might get caught in this search, you will sadly (and slowly) have to use window.getComputedStyle(). The function in that case might be:

//Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    var style = window.getComputedStyle(el);
    return (style.display === 'none')
}

选项#2可能更简单一些,因为它占据了更多的边缘案例,但我认为它的速度要慢一点,所以如果你必须重复这个操作很多次,最好避免它。

Option #2 is probably a little more straightforward since it accounts for more edge cases, but I bet its a good deal slower, too, so if you have to repeat this operation many times, best to probably avoid it.

这篇关于检查元素是否在DOM中可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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