How to check element's visibility via javascript?

后端 未结 5 1422
后悔当初
后悔当初 2020-12-05 11:14

I\'m interested in a way to check whether an element has display:none style explicility (ie style=\"display:none\"), has a class that has (or inherits) this style, or one of

5条回答
  •  离开以前
    2020-12-05 11:42

    You are looking for one solution to two different scenarios.

    The first scenario is getting the cascaded/computed style for a css property. See this answer for how to do that.

    The second scenario is detecting if any of an element's parents are hidden. This requires traversing and is cumbersome and slow.

    You can take the solution outlined here (and employed by jQuery/Sizzle since 1.3.2), and just read the dimensions of the element:

    var isVisible = element.offsetWidth > 0 || element.offsetHeight > 0;
    

    If it has dimensions then it is visible in the sense that it takes up some rectangular space (however small) in the document. Note that this technique still has some downsides for certain elements in certain browsers, but should work in most cases.

提交回复
热议问题