根据此 MDN 文档,每当元素或其任何父元素通过显示样式属性隐藏时,该元素的属性就会返回。只需确保元素不是固定的。如果页面上没有元素,则用于检查此内容的脚本可能如下所示:offsetParent
null
position: fixed;
// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
return (el.offsetParent === null)
}
另一方面,如果您确实有可能在此搜索中捕获的位置固定元素,那么您将遗憾地(并且缓慢地)不得不使用window.getComputedStyle()
。在这种情况下,函数可能是:
// 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可能更直接一些,因为它考虑了更多的边缘情况,但我敢打赌它的速度也慢了很多,所以如果你必须多次重复此操作,最好避免它。