How to check element's visibility via javascript?

后端 未结 5 1427
后悔当初
后悔当初 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:49

    The above solution caters for this "invisibility" scenario:

    display:none;
    

    but it does not cater for this one:

    visibility: hidden;
    

    In order to include the test for visibility: hidden; the script can be modified as follows...

    First, create a cross browser compliant function to get the desired element's computed style:

    computedStyle = function(vElement) {
      return window.getComputedStyle?
             ?window.getComputedStyle(vElement,null)
             :vElement.currentStyle;                    //IE 8 and less
    }
    

    Second, create the function to test for visibility

    isVisible = function(vElement) {
      return !(vElement.offsetWidth == 0 && vElement.offsetHeight == 0)
             && computedStyle(vElement).visibility != "hidden";  
    }
    

    Finally, simply reference the isVisible function wherever needed as follows:

    if (isVisible(myElement)) {
      alert('You can see me!');
    } else {
      alert('I am invisible ha ha!');
    }
    

    Just a note that the current isVisible() tests do not cater for a number of "invisibility" scenarios (however the tests could I suppose be enhanced to include these). Here are a few examples:

    1. where an element is the same colour as the surrounding colour
    2. where an element is visible but physically behind another element eg. different z-index values

    It is also probably worth noting the following regarding the above computedStyle() function:

    1. It can of course be used for many other style related purposes besides testing visibility
    2. I have opted to ignore :pseudo style testing due to patchy browser support, however with a minor modification to the function this could be included if desired.

提交回复
热议问题