javascript - trick to test visibility of an element

though there is a visible property that you can test if a element is having the visibility set to true (display = none), however, it is more arguable why not just to test the offsetWidth and the offsetHeight property, thought it looks crude, but it shold be incredibly effecient in that if a width and height is 0, then even if the display is not none, you will not be able to see it on the screen.

 

however, there is one exception for the height and width test, it is because that IE has tr return width or height as 0; so we have the following code. 

 

 

<html>
<head>
<title>Visibility Test</title>
<script type="text/javascript">
  function isVisible(elem) {
    var isTR = elem.nodeName.toLowerCase() === "tr",
w = elem.offsetWidth, h = elem.offsetHeight;
    return w !== 0 && h !== 0 && !isTR ?
      true :
      w === 0 && h === 0 && !isTR ?
        false :
        computedStyle(elem, "display") === "none";
  }
  window.onload = function () {
    var block = document.getElementById("block");
    var none = document.getElementById("none");
    // Alerts out 'true'
    alert(isVisible(block));
    // Alerts out 'false'
    alert(isVisible(none));
  };
</script>
</head>
<body>
<div id="block">Test</div>
<div id="none" style="display:none;">Test</div>
</body>
</html>
 

 

你可能感兴趣的:(JavaScript)