javascript - trick to get and set height and width

本文介绍了一种可靠的方法来获取隐藏或可见HTML元素的真实高度和宽度,包括内边距,并提供了一个JavaScript示例,演示如何通过临时调整元素样式来准确测量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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>
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值