HTML元素(div)的全高,包括边框,内边距和边距?


75

我需要一个div的全高,我目前正在使用

document.getElementById('measureTool').offsetHeight

offsetHeight -返回元素的高度,包括边框和填充(如果有),但不包括边距

但是div中的一个嵌套元素具有margin-top20%,因此我得到了错误的度量。我试图style.marginTopscrollHeight没有成功。

如何在javascript中获取元素(div)的完整高度(边框,边距,边距)?

如果没有其他办法,我可以使用jQuery。

Answers:


68

如果可以使用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);
}

现场演示

代码源


我非常希望不要这样做(该项目实际上不是网页)。但是,感谢您的jQuery解决方案和快速答复!:)
Edza

3
每次使用getElementById遍历整个DOM都是不好的代码,既浪费CPU时间,又浪费更多代码。编辑答案,将榆木缓存在变量中。
Vitim.us 2012年

在OP询问的情况下,以上代码似乎不起作用。看到这个小提琴:jsfiddle.net/3e2y1j0s/1。(添加1px的填充会使报告的高度加倍。)
克里斯·米德尔顿

1
另外,请注意,jQuery可以报告忽略第一个孩子的上边距和最后一个孩子的下边距的externalHeight -请参见stackoverflow.com/questions/9770248/…
赛车Ta

1
非jquery解决方案获取元素的内容高度+两个边距,但忽略填充和边框(以及最终的滚动条)jsfiddle.net/3e2y1j0s/3
jvilhena

72

像这样的东西(没有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


21
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

谢谢。这是对该解决方案的一些优化:```<!-语言:lang-js->函数getElementHeight(el){const $ elComputedStyle = getComputedStyle(el); 返回el.offsetHeight + parseInt($ elComputedStyle.getPropertyValue('margin-top')+ $ elComputedStyle.getPropertyValue('margin-bottom'),10); }`
-bboydflo

12

使用箭头功能的另一个功能解决方案:

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
马丁

10

依次使用所有道具,边距,边框,边距和高度。

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)
}

parseInt基数参数设置不正确。我试图编辑您的答案,但是编辑必须更改至少6个字符:/
Jespertheend

好的,.map(k => parseInt(style.getPropertyValue(k)), 10)应该是.map(k => parseInt(style.getPropertyValue(k), 10))
Jespertheend '19

8

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,我对其进行了少许修改,并将其放入我的帮助器集合中。我希望可以吗?
拉斐尔

1
@Raphael谢谢!当然,我也做过同样的
事情

7

香草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')));

0

在Vanilla JS中,在函数getAllmargin中,我们获得了顶部和底部的边距之和,并通过clientHeight获得了包括所有填充的高度

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));

-1

较早的解决方案可能是理想的。为了找到一种简单的方法,我想出了类似的方法。这会将目标包装在中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;
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.