91

現在使用しているdivの全高が必要です

document.getElementById('measureTool').offsetHeight

offsetHeight- 要素の高さを返します。境界線とパディングがある場合はそれを含めますが、余白は含みません。

しかし、div 内のネストされた要素の 1 つに of があるmargin-topため20%、測定値が間違っています。私は試してみましたが、成功しませんでしたstyle.marginTopscrollHeight

JavaScriptで要素(div)の全高(ボーダー、パディング、マージン)を取得するにはどうすればよいですか?

他に方法がない場合は、jQuery で問題ありません。

4

10 に答える 10

76

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

ライブ デモ

コードソース

于 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 に答える
6

古いもの-とにかく...ここにいるすべての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')));
于 2014-12-09T22:02:41.330 に答える