91

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

document.getElementById('measureTool').offsetHeight

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

但是 div 内的一个嵌套元素有一个margin-topof 20%,所以我得到了错误的测量结果。我试过了style.marginTopscrollHeight但没有成功。

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

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

4

10 回答 10

97

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

于 2014-05-20T00:47:21.477 回答
76

如果你可以使用 jQuery:

$('#divId').outerHeight(true) // gives with margins.

jQuery 文档

对于 vanilla 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);
}

​现场 演示

代码源

于 2012-05-28T16:32:07.567 回答
25
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/

我认为这个解决方案更具可读性,但是所提供的解决方案都没有考虑到不是像素的大小...... :(

于 2016-02-05T19:14:33.170 回答
14

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

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);
于 2017-11-28T16:26:16.030 回答
12

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)
}
于 2019-01-08T16:02:16.750 回答
11

依次使用所有道具、边距、边框、填充和高度。

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)
}
于 2019-01-17T20:33:20.713 回答
10

原版 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>

于 2018-05-23T14:13:31.720 回答
6

旧的 - 无论如何......对于所有 jQuery-banning 和快捷方式的人来说,这里有一些附加脚本,它扩展了其他答案的维度/getabsoluteheight 方法:

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')));
于 2014-12-09T22:02:41.330 回答
3

早期的解决方案可能是理想的。为了寻找一种简单的方法,我想出了类似的方法。这将目标包装在一个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;
于 2019-03-12T21:08:54.403 回答
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));
于 2020-02-11T12:45:50.570 回答