Check if element is visible in DOM

后端 未结 18 2079

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

So, for example, in this page: Performance Bikes, if you hover over Deals (on the

18条回答
  •  梦谈多话
    2020-11-22 07:51

    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)
    }
    

    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')
    }
    

    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.

提交回复
热议问题