javascript-trick to test visibility of an element

1706 ワード

though there is a visible propertythaat can test iiifea elemen is having the visibility set to true(display=none)、however、itismoreable ablehu juuuht t to test the ofsetWidth and the the fsefsetwidth the the the fsefsesefsetfset the the the fsefsefset the the fsefsefsetHefsesetttHefseitititeeeeeeeeeeeeeeeeeeeeefffffffftytytytytytytytytyを選択します.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 follwing 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>