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可能更直接一些,因为它可以解决更多的情况,但是我敢打赌,它的速度也要慢得多,因此,如果您必须重复执行多次此操作,最好避免这种情况。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…