javascript - trick to get and set height and width

 

when looking at properties that could have an auto value, it was mentioned that height and width are two properties that frequently have these values.

 

 

the offsetHeight and offsetWidth properties provide just that: A fairly reliable place to access the correct height and width of an element. The numbers returned by the two properties include the padding of the element as well.

 

this is all well, but there is one gotcha, though that if hte element is hidden, the offsetWidth an offsetHeight will be 0; so we hae to take a woraround to temporarily make the element visible, but in a hidden state.

 

achieve this by setting the display property to block (making it visible and able to be measured) and immediately set its visibility to hidden (making it invisible to the user) and finally set its position to absolute (taking it out of the flow of the document, stopping it from pushing any other elements out of the way)

 

below shows the code sample how to do that. 

 

 

 

<html>
<head>
<title>Height/Width Test</title>
<script type="text/javascript">
  (function () {
    this.height = function (elem) {
      return this.offsetHeight ||
      swap(elem, props, function () {
        return elem.offsetHeight;
      });
    };
    this.width = function (elem) {
      return this.offsetWidth ||
        swap(elem, props, function () {
          return elem.offsetWidth;
      });
    };
    var props = {
      position: "absolute",
      visibility: "hidden",
      display: "block"
    };
    // the wap function will temporary set the 
    // e.g. positoin to be "absolute"
    //      visiblity to be "hidden"
    // after retrieve the value, store the old value back 
    function swap(elem, options, callback) {
      var old = {}, ret;
      // Remember the old values, and insert the new ones
      for (var name in options) {
        old[name] = elem.style[name];
        elem.style[name] = options[name];
      }
      ret = callback();
      // Revert the old values
      for (var name in options) {
        elem.style[name] = old[name];
      }
      return ret;
    }
  })();
  window.onload = function () {
    var block = document.getElementById("block");
    var none = document.getElementById("none");
    // Both will alert out the same values
    alert(width(block) + " " + height(block));
    alert(width(none) + " " + height(none));
  };
</script>
</head>
<body>
<div id="block">Test</div>
<div id="none" style="display:none;">Test</div>
</body>
</html>
 

你可能感兴趣的:(JavaScript)