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

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

问题描述

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

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

例如,在此页面中:Performance Bikes,如果您将鼠标悬停在交易(在顶部菜单上),交易窗口出现,但在开始时没有显示.它在 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 元素,我如何检查它是否可见?我试过了:

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天全站免登陆