美文网首页
js如何判断element 是否隐藏

js如何判断element 是否隐藏

作者: 星星赐福 | 来源:发表于2020-07-13 15:22 被阅读0次

根据MDN文档的说明, 以下三种情况 HTMLElement.offsetParent 会返回 null

  • 该节点或其父节点display属性为 none
  • 该节点的 position 属性设为 fiexed
  • 该节点为<body><html>

所以可以根据 HTMLElement.offsetParent 来判断改节点是否隐藏

function isHidden(el) {
    return (el.offsetParent === null)
}

如果你要判断的节点恰好 position:fiexed,那么可以通过window.getComputedStyle() 判断:

function isHidden(el) {
    var style = window.getComputedStyle(el);
    return (style.display === 'none')
}

相比第一种方案,第二种会慢很多,如果要做重复的判断,不建议使用第二种

相关文章

网友评论

      本文标题:js如何判断element 是否隐藏

      本文链接:https://www.haomeiwen.com/subject/lcwacktx.html