Javascript html 元素 (div) 的全高,包括边框、填充和边距?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10787782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:55:48  来源:igfitidea点击:

Full height of a html element (div) including border, padding and margin?

javascriptcss

提问by Edza

I need the full height of a div, I'm currently using

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

document.getElementById('measureTool').offsetHeight

offsetHeight- Returns the height of an element, including borders and padding if any, but not margins

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

But one of the nested elements inside the div, has a margin-topof 20%, so I get a wrong measurement. I tried style.marginTopand scrollHeightwithout success.

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

How can I get the full height (border, padding, margin) of an element (div) in javascript?

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

If there isn't any other way I'm ok with jQuery.

如果没有任何其他方式,我可以使用 jQuery。

采纳答案by gdoron is supporting Monica

If you can use jQuery:

如果你可以使用jQuery:

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

jQuery docs

jQuery 文档

For vanilla javascript you need to write a lot more (like always...):

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

? Live DEMO

? 现场演示

code source

代码源

回答by thetallweeks

What about something like this (no jquery)? It's similar to @gdoron's answer but a little simpler. Tested it in IE9+, Firefox, and Chrome.

这样的东西怎么样(没有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);
}

Here is a working jsfiddle.

这是一个有效的 jsfiddle

回答by corysimmons

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/

https://jsfiddle.net/gbd47ox1/

I think this solution is more readable, but none of the solutions presented account for sizes that aren't pixels... :(

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

回答by EricD

Another functional solution using arrow functions:

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

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

回答by qdev

Vanilla JavaScript ECMAScript 5.1

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

回答by Quicker

old one - anyway... for all jQuery-banning and shortcut folks out there here is some plus scripting which expands the dimension/getabsoluteheight approaches of the other answers:

旧的 - 无论如何......对于所有禁止 jQuery 和快捷方式的人来说,这里有一些附加脚本,它扩展了其他答案的维度/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')));

回答by Muhammad Adeel

Use all the props, margin, border, padding and height in sequence.

按顺序使用所有道具、边距、边框、内边距和高度。

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

回答by Fabian von Ellerts

qdev wrote a nice solution, however I think offsetHeight is faster and better supported than getBoundingClientRect(). I also used ES6 to reduce the code size.

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

回答by David Khakim

in Vanilla JS in the function getAllmargin we get the sum of both margin top and bottom and with clientHeight we get the height including all paddings

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

回答by Bogdan Pasterak

The earlier solutions are probably ideal. In search of an easy way, I came up with something like that. This wraps the target in a div. The height of the divis already calculated and rounded.

较早的解决方案可能是理想的。为了寻找一种简单的方法,我想出了类似的方法。这将目标包装在一个div. 的高度div已经计算并四舍五入。

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

and in JavaScript:

在 JavaScript 中:

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