You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用getPropertyValue获取元素高度错误,如何获取真实高度?

上述代码执行后弹出18px,但该div元素的实际高度为48px,显然getPropertyValue未将padding计算在内。请问如何获取元素的真实高度?


解决方法

以下几种方式可以获取包含内边距的元素真实高度:

  • offsetHeight属性:返回元素的总像素高度,包含内容高度、内边距(padding)和边框(border),不包含外边距(margin)。

    const elem = document.querySelector(".d1");
    alert(elem.offsetHeight); // 示例中返回48px
    
  • clientHeight属性:返回元素内部高度,包含内容和内边距,不含边框、外边距及滚动条(如果存在)。示例中无边框,结果和offsetHeight一致。

    const elem = document.querySelector(".d1");
    alert(elem.clientHeight);
    
  • getBoundingClientRect()方法:返回DOMRect对象,其中的height属性包含内容、内边距和边框的总高度。

    const elem = document.querySelector(".d1");
    const rect = elem.getBoundingClientRect();
    alert(rect.height);
    

注:getComputedStyle获取的height是内容高度,仅对应盒模型里的content部分,不包含padding和border,这是标准行为。


内容的提问来源于stack exchange,提问作者darkchampionz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:01:12