Check if element is visible in DOM

后端 未结 18 1714

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条回答
  •  -上瘾入骨i
    2020-11-22 07:50

    So what I found is the most feasible method:

    function visible(elm) {
      if(!elm.offsetHeight && !elm.offsetWidth) { return false; }
      if(getComputedStyle(elm).visibility === 'hidden') { return false; }
      return true;
    }
    

    This is build on these facts:

    • A display: none element (even a nested one) doesn't have a width nor height.
    • visiblity is hidden even for nested elements.

    So no need for testing offsetParent or looping up in the DOM tree to test which parent has visibility: hidden. This should work even in IE 9.

    You could argue if opacity: 0 and collapsed elements (has a width but no height - or visa versa) is not really visible either. But then again they are not per say hidden.

提交回复
热议问题