Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

javascript - 检查元素在DOM中是否可见(Check if element is visible in DOM)

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

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

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.

(因此,例如,在此页面: Performance Bikes中 ,如果将鼠标悬停在Deals上(在顶部菜单上),则会显示一个交易窗口,但一开始并未显示。)

It is in the HTML but it is not visible.

(它在HTML中,但不可见。)

So, given a DOM element, how can I check if it is visible or not?

(那么,给定一个DOM元素,如何检查它是否可见?)

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?

(还有其他我可能会想念的东西吗?)

  ask by Hommer Smith translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(根据此MDN文档 ,每当offsetParent或元素的任何父offsetParent通过display style属性被隐藏时,该元素的offsetParent属性将返回null 。)

Just make sure that the element isn't fixed.

(只要确保该元素未固定即可。)

A script to check this, if you have no position: fixed;

(如果没有position: fixed; ,请使用脚本来检查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)
}

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() .

(另一方面,如果您确实有位置固定的元素可能会在此搜索中被捕获,您将不得不(缓慢地)使用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')
}

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.

(选项#2可能更直接一些,因为它可以解决更多的情况,但是我敢打赌,它的速度也要慢得多,因此,如果您必须重复执行多次此操作,最好避免这种情况。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...