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

Edz*_*dza 58 javascript css

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

document.getElementById('measureTool').offsetHeight
Run Code Online (Sandbox Code Playgroud)

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

但在div里面嵌套元素之一,拥有margin-top20%,所以我得到一个错误的测量.我试图style.marginTopscrollHeight没有成功.

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

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

gdo*_*ica 62

如果你可以使用jQuery:

$('#divId').outerHeight(true) // gives with margins.
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

现场演示

代码源

  • 每次使用getElementById遍历整个DOM都是错误的代码,浪费了cpu时间,还有更多的代码.编辑你的答案,将榆树缓存在一个变量中. (3认同)

the*_*eks 57

这样的事情(没有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);
}
Run Code Online (Sandbox Code Playgroud)

这是一个工作的jsfiddle.


cor*_*ons 13

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);
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/gbd47ox1/

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


Fab*_*rts 11

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)
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*icD 8

使用其它功能性溶液箭头功能:

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);
Run Code Online (Sandbox Code Playgroud)

  • 你可能想添加 `margin-top` 和 `margin-bottom` (2认同)

Qui*_*ker 5

旧的-无论如何...对于所有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')));
Run Code Online (Sandbox Code Playgroud)


qde*_*dev 5

香草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';
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
<div id="myID">element</div>
<div class="result"></div>
Run Code Online (Sandbox Code Playgroud)


Muh*_*eel 5

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

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)
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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

<div style="margin: 0; padding: 0; border: none;">
    <p class="target">something info ex</p>
</div>
Run Code Online (Sandbox Code Playgroud)

在 JavaScript 中:

var height = document.querySelector(".target").parentElement.offsetHeight;
Run Code Online (Sandbox Code Playgroud)