一个HTML元素(div)的完整高度,包括边框、内边距和外边距是多少?

109

我需要一个div的完整高度,目前我正在使用

document.getElementById('measureTool').offsetHeight

offsetHeight - 返回一个元素的高度,包括任何边框和内边距,但不包括外边距。

但是 div 元素中的一个嵌套元素具有 margin-top20%,所以会导致测量结果错误。我尝试使用 style.marginTopscrollHeight ,但没有成功。

如何使用 JavaScript 获取一个元素(div)的完整高度(边框、内边距、外边距)?

如果没有别的方法,我可以接受使用 jQuery。

10个回答

115

这个怎么样(没有使用jQuery)?它与@gdoron的答案类似,但更简单。在IE9+、Firefox和Chrome中测试过。

function getAbsoluteHeight(el) {
  // Get the DOM Node if you pass in a string
  el = (typeof el === 'string') ? document.querySelector(el) : el; 

  var styles = window.getComputedStyle(el);
  var margin = parseFloat(styles['marginTop']) +
               parseFloat(styles['marginBottom']);

  return Math.ceil(el.offsetHeight + margin);
}

这里有一个可以工作的 jsfiddle


84
如果您能使用jQuery:
$('#divId').outerHeight(true) // gives with margins.

jQuery文档

如果使用纯JavaScript,需要编写更多代码(总是这样...):

function Dimension(elmID) {
    var elmHeight, elmMargin, elm = document.getElementById(elmID);
    if(document.all) {// IE
        elmHeight = elm.currentStyle.height;
        elmMargin = parseInt(elm.currentStyle.marginTop, 10) + parseInt(elm.currentStyle.marginBottom, 10) + "px";
    } else {// Mozilla
        elmHeight = document.defaultView.getComputedStyle(elm, '').getPropertyValue('height');
        elmMargin = parseInt(document.defaultView.getComputedStyle(elm, '').getPropertyValue('margin-top')) + parseInt(document.defaultView.getComputedStyle(elm, '').getPropertyValue('margin-bottom')) + "px";
    }
    return (elmHeight+elmMargin);
}

实时演示

代码来源


3
每次使用 getElementById 遍历整个 DOM 是糟糕的代码,会浪费 CPU 时间,而且需要更多的代码。我编辑了你的答案,将元素储存在一个变量中以实现缓存。 - Vitim.us
1
另外,请注意jQuery可以报告一个outerHeight,它忽略了第一个子元素的顶部边距和最后一个子元素的底部边距 - 请参见https://dev59.com/qWHVa4cB1Zd3GeqPpbMZ#28121477。 - Racing Tadpole
1
非jQuery解决方案获取元素内容的高度加上两个外边距,但忽略填充和边框(以及可能出现的滚动条)http://jsfiddle.net/3e2y1j0s/3/ - jvilhena
1
此解决方案假定边距仅以像素为单位定义。对于任何未以像素为单位定义的边距,它将返回不正确的结果。 - Keith F. Kelly
撇开像素(px)这个问题不谈,这个纯净的JS示例简直是超越了预期的领域。 - undefined
显示剩余3条评论

28
var el = document.querySelector('div');

var elHeight = el.offsetHeight;
elHeight += parseInt(window.getComputedStyle(el).getPropertyValue('margin-top'));
elHeight += parseInt(window.getComputedStyle(el).getPropertyValue('margin-bottom'));

console.log(elHeight);

我认为这个解决方案更易读,但是没有一个呈现的解决方案考虑到不是像素的尺寸... :(

https://jsfiddle.net/gbd47ox1/


当我使用“em”设置高度时,似乎可以正确获取计算出的高度(以像素为单位)? - user2490003
也许吧。不过最好在各种浏览器中测试一下,因为它们都有不同的亚像素舍入技术。 - corysimmons
谢谢。这是对该解决方案的轻微优化:```<!-- language: lang-js --> function getElementHeight(el) { const $elComputedStyle = getComputedStyle(el); return el.offsetHeight + parseInt($elComputedStyle.getPropertyValue('margin-top') + $elComputedStyle.getPropertyValue('margin-bottom'), 10); } ``` - bboydflo

16

使用 箭头函数 的另一种功能性解决方案:

let el = document.querySelector('div');
let style = window.getComputedStyle(el);
let height = ['height', 'padding-top', 'padding-bottom']
        .map((key) => parseInt(style.getPropertyValue(key), 10))
        .reduce((prev, cur) => prev + cur);

2
你可能想要添加 margin-topmargin-bottom - xyhhx
1
注意,样式高度中已经包含了填充,但你可能需要按建议添加边距。 - Picard
不要考虑将 padding-toppadding-bottom 计算到总高度中,因为它们已经被添加到 height 中,再次计算会得出错误的总高度。 - Ali Hussnain - alichampion

14

qdev写了一个好的解决方案,但我认为offsetHeight比getBoundingClientRect()更快、更受支持。我还使用ES6来减小代码大小。

/**
 * Returns the element height including margins
 * @param element - element
 * @returns {number}
 */
function outerHeight(element) {
    const height = element.offsetHeight,
        style = window.getComputedStyle(element)

    return ['top', 'bottom']
        .map(side => parseInt(style[`margin-${side}`]))
        .reduce((total, side) => total + side, height)
}

我真的很喜欢这个风格@fabian-von-ellerts,我稍微修改了一下并放到我的帮助集合中。希望这样可以吗? - Raphael
1
@Raphael 谢谢!当然,我也是这么做的哈哈哈 - Fabian von Ellerts

12

按照顺序使用所有的道具,包括margin、border、padding和height。

function getElmHeight(node) {
    const list = [
        'margin-top',
        'margin-bottom',
        'border-top',
        'border-bottom',
        'padding-top',
        'padding-bottom',
        'height'
    ]

    const style = window.getComputedStyle(node)
    return list
        .map(k => parseInt(style.getPropertyValue(k), 10))
        .reduce((prev, cur) => prev + cur)
}

1
parseInt函数的基数参数未被正确设置。我尝试编辑您的答案,但编辑必须至少更改6个字符 :/ - Jespertheend
1
好的,确保 .map(k => parseInt(style.getPropertyValue(k)), 10) 应该是 .map(k => parseInt(style.getPropertyValue(k), 10)) - Jespertheend

11

纯JavaScript ECMAScript 5.1

var element = document.getElementById('myID'),
    height = element.getBoundingClientRect().height,
    style = window.getComputedStyle(element);
    
// height: element height + vertical padding & borders
// now we just need to add vertical margins
height = ["top", "bottom"]
  .map(function(side) {
    return parseInt(style['margin-' + side], 10)
  })
  .reduce(function(total, side) {
    return total + side
  }, height)
  
// result: compare with devtools computed measurements
document.querySelector('.result').innerText = 'Total height is: ' + height + 'px';
#myID {
  padding: 10px 0 20px;
  border-top: solid 2px red;
  border-bottom: solid 3px pink;
  margin: 5px 0 7px;
  background-color: yellow;
}

.result {
  margin-top: 50px;
}
<div id="myID">element</div>
<div class="result"></div>


6

旧的方法 - 无论如何...对于所有不使用jQuery和快捷方式的人,这里是一些扩展其他答案中维度/获取绝对高度方法的脚本:

function getallinheight(obj) {
  var compstyle=(typeof window.getComputedStyle==='undefined')?obj.currentStyle:window.getComputedStyle(obj);
  var marginTop=parseInt(compstyle.marginTop);
  var marginBottom=parseInt(compstyle.marginBottom);
  var borderTopWidth=parseInt(compstyle.borderTopWidth);
  var borderBottomWidth=parseInt(compstyle.borderBottomWidth);
  return obj.offsetHeight+
         (isNaN(marginTop)?0:marginTop)+(isNaN(marginBottom)?0:marginBottom)+
         (isNaN(borderTopWidth)?0:borderTopWidth)+(isNaN(borderBottomWidth)?0:borderBottomWidth);
}
alert(getallinheight(document.getElementById('measureTool')));

5

前面的解决方案可能是最理想的。在寻找简单方法时,我想到了类似于这样的东西。这将目标包装在一个div中。 div的高度已经被计算并四舍五入。

<div style="margin: 0; padding: 0; border: none;">
    <p class="target">something info ex</p>
</div>

在 JavaScript 中:

var height = document.querySelector(".target").parentElement.offsetHeight;

如果您可以控制HTML,那么这将变得非常简单。谢谢! - Warren Spencer

0

使用原生JS,在函数getAllmargin中,我们获取了上下边距的总和,并且通过clientHeight获取了包括所有padding在内的高度。

var measureTool = document.getElementById('measureTool');
function getAllmargin(elem){
//Use parseInt method to get only number
        return parseInt(window.getComputedStyle(elem, null).getPropertyValue('margin-top')) 
        + parseInt(window.getComputedStyle(elem, null).getPropertyValue('margin-bottom'));
}
//Finally we get entire height  
console.log(measureTool.clientHeight + getAllmargin(measureTool));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接