JavaScriptでドキュメント全体の高さを取得する方法は?


333

一部のドキュメントでは、ドキュメントの高さを取得できません(何かを絶対に一番下に配置するため)。さらに、上のパディングボトムはこれらのページでは何もしないようですが、高さが返されるページで行います。適切な事例:

http://fandango.com
http://paperbackswap.com

Fandangoでは、
jQuery $(document).height();は正しい値を
document.height返します0
document.body.scrollHeightは0を返します

ペーパーバックスワップ時:
jQueryの$(document).height();TypeError:$(document)is null
document.heightが不正な値を
document.body.scrollHeight返し、不正な値を返します

注:トリックがある場合は、ブラウザレベルの権限があります。


5
$(文書)そのサイトは、jQueryのがロードされていないため、nullです...
ジェームズ

ええと、jQueryが登録されていることを確認するために何か他のものをチェックしたと誓ったかもしれませんが、私のようには見えません、HA!firebugにはjQueryがパッケージ化されていると思いました...ええと、それが解決策であるなら、これをチェックするつもりです。
ニック

4
firebugにはjQUeryがパッケージ化されていません
harsimranb 2012

ブラウザウィンドウのサイズを確認するを参照してください。さまざまなブラウザの動作の優れた表があります。
Oriol

回答:


670

ドキュメントのサイズは、すべてのブラウザーがclientHeightプロパティとscrollHeightプロパティを公開しているものの、値の計算方法にすべてが一致しているわけではないため、ブラウザー互換性の悪夢です。

正しい高さ/幅をテストする方法については、以前は複雑なベストプラクティス式がありました。これには、利用可能な場合はdocument.documentElementプロパティの使用、またはドキュメントプロパティの使用などが含まれます。

正しい高さを取得する最も簡単な方法は、ドキュメントまたはdocumentElementにあるすべての高さの値を取得し、最も高い値を使用することです。これは基本的にjQueryが行うことです:

var body = document.body,
    html = document.documentElement;

var height = Math.max( body.scrollHeight, body.offsetHeight, 
                       html.clientHeight, html.scrollHeight, html.offsetHeight );

Firebug + jQueryブックマークレットを使用した簡単なテストでは、引用された両方のページの正しい高さが返され、コード例も返されます。

ドキュメントの準備ができる前にドキュメントの高さをテストすると、常に0になることに注意してください。さらに読み込むものがある場合、またはユーザーがウィンドウのサイズを変更した場合は、再テストが必要になる場合があります。ロード時にこれが必要な場合はonload、またはdocument readyイベントを使用します。それ以外の場合は、必要なときにいつでもテストしてください。


2
プロトタイプライブラリを使用しているときに機能するため、このソリューションを評価してください
。jQuery

10
iframeとjqueryを使用する場合、この計算方法のため、iframeのドキュメントの高さは常に少なくともiframe自体の高さになります。これは、コンテンツに合わせてiframeの高さを下げる場合に注意することが重要です。最初にiframeの高さをリセットする必要があります。
David Lay、

3
私はiframeを拡大して縮小する必要があり(facebookアプリ)、document.body.offsetHeightが最適で、ほとんどのブラウザーで正確にサポートされていました。
JeffG 2012

1
これはすばらしいことですが、ドキュメントの準備ができていない場合、つまりサーバーで生成されたコードで使用された場合に誤った結果が生じる可能性があります...
stuartdotnet

1
準備ができる前にドキュメントをテストすることはできません。これは、生成されたコード/ドキュメントとは関係ありませんが、ドキュメントのロード方法です。テストはドキュメントの準備が整った後で実行する必要があります。ドキュメントが完全に読み込まれたときにのみ実行することをお勧めします。残りのアイテムが高さに影響し、ブラウザーのサイズも変更される可能性があるためです。
Borgar

212

これは本当に古い質問なので、多くの古い回答があります。2020年の時点で、すべての主要なブラウザーがこの標準に準拠しています。

2020年の回答:

document.body.scrollHeight

編集:上記は<body>タグのマージンを考慮していません。体に余裕がある場合は、次を使用します。

document.documentElement.scrollHeight

hm-今テストしてみました-理由はわかりません-わかりました:)-以前のコメントを削除しました
KamilKiełczewski2017年

6
2017年の時点で、これは私に対する正しい答えとしてマークされているはずです。
Joan

@Joan決定するのは元のポスター
次第です

マージンがある場合は機能しません。document.documentElement.getBoundingClientRect()うまく機能します。
torvin 2017年

3
これには1つのエラーがあります。たとえば、デフォルトのマージンを持つ<h1>の最初に要素がある<body>とすると、それ<body>を検出する方法なしに要素が押し下げられます。document.documentElement.scrollHeight(ではないdocument.body,scrollHeight)が最も正確な方法です。これは、ボディマージンとボディの下にあるもののマージンの両方で機能します。
イーサン

29

これを使うこともできます:

var B = document.body,
    H = document.documentElement,
    height

if (typeof document.height !== 'undefined') {
    height = document.height // For webkit browsers
} else {
    height = Math.max( B.scrollHeight, B.offsetHeight,H.clientHeight, H.scrollHeight, H.offsetHeight );
}

またはよりjQueryの方法で(あなたが言ったようにjQueryは嘘をつかないので):)

Math.max($(document).height(), $(window).height())

24

完全なドキュメントの高さの計算:

より一般的になり、ドキュメントの高さを見つけるには、単純な再帰で現在のページで最も高いDOMノードを見つけるだけです。

;(function() {
    var pageHeight = 0;

    function findHighestNode(nodesList) {
        for (var i = nodesList.length - 1; i >= 0; i--) {
            if (nodesList[i].scrollHeight && nodesList[i].clientHeight) {
                var elHeight = Math.max(nodesList[i].scrollHeight, nodesList[i].clientHeight);
                pageHeight = Math.max(elHeight, pageHeight);
            }
            if (nodesList[i].childNodes.length) findHighestNode(nodesList[i].childNodes);
        }
    }

    findHighestNode(document.documentElement.childNodes);

    // The entire page height is found
    console.log('Page height is', pageHeight);
})();

このスクリプトをDevTools Consoleに貼り付けて、サンプルサイト(http://fandango.com/またはhttp://paperbackswap.com/)でテストできます。

注:で動作していIframesます。

楽しい!


2
これは魅力のように働きました!ここで他の答えは全高(スクロール可能領域を含む)を取得するために機能しません。それらはすべて可視領域の高さのみを返します。
Martin Kristiansson

本当に例外的で、これを考えたことはありません。たった1人だけがphantomjsで動作しています。
MindlessRanger

6

ドキュメントのサイズを決定する "jQueryメソッド"-すべてをクエリし、最高の値を取り、最高のものを期待する-はほとんどの場合に機能しますが、すべてに機能するわけではありません

ドキュメントサイズの防弾結果が本当に必要な場合は、jQuery.documentSizeプラグインを使用することをお勧めします。他のメソッドとは異なり、ロードされたときのブラウザの動作を実際にテストおよび評価し、その結果に基づいて、そこから正しいプロパティをクエリします。

この1回限りのテストによるパフォーマンスへの影響は最小限であり、プラグインは奇妙なシナリオでも正しい結果を返します。私がそう言ったからではなく、自動生成された大規模なテストスイートが実際にそれを確認するためです。

プラグインはバニラJavaScriptで記述されているため、jQueryなしでも使用できます。


5

嘘をついた、jQueryは両方のページに対して正しい値を返します$(document).height(); ...なぜ私はそれを疑ったのですか?


1
異なるブラウザ仲間。
jahrichie 2015

4

2017年の正しい答えは次のとおりです。

document.documentElement.getBoundingClientRect().height

document.body.scrollHeightこの方法とは異なり、体のマージンを考慮します。また、一部の高さの値も提供します。これは、場合によっては役立ちます。


1
これらは私がこのページにあなたの方法を試してみたときに、私が得る結果である:i.imgur.com/0psVkIk.pngあなたのメソッドの戻りを何かウィンドウの高さのように見え、しばらくそのdocument.body.scrollHeight元の質問が尋ねているリスト全体のスクロール可能な高さ、。
マルキッツォ

2
@Marquizzoこれはhtml { height: 100% }、このページにCSS があるためです。したがって、APIは実際に計算された高さを正しく返します。このスタイルを削除してマージンを追加してみてください。body使用すると何が問題になるかがわかりますdocument.body.scrollHeight
torvin 2017年

これには1つのエラーがあります。たとえば、デフォルトのマージンを持つ<h1>の最初に要素がある<body>とすると、それ<body>を検出する方法なしに要素が押し下げられます。document.documentElement.scrollHeight(ではないdocument.body,scrollHeight)が最も正確な方法です。
イーサン

@Booligoosh意味がわからない。documentElement.scrollHeightこの場合、誤った値を返します。documentElement.getBoundingClientRect().height正しいものを与える。これをチェックしてください:jsfiddle.net/fLpqjsxd
torvin

1
@torvin事実は、意図した結果がによって返されないことに変わりはありませんgetBoundingClientRect().height。他の3つ(3つ)のメソッドは回避されませんが、それは回避されます。あなたがそれに劣ると言及したものを含みます。そして、このページのhtmlの高さから100%を削除することを提案し、それにマージンを追加することで、そうすることを主張します。ポイントは何ですか ?それを受け入れるだけgetBoundingClientRect().heightでも、防弾ではありません。
Rob Waa

2

クロスブラウザー/デバイスの方法で幅を取得するには、以下を使用します。

function getActualWidth() {
    var actualWidth = window.innerWidth ||
                      document.documentElement.clientWidth ||
                      document.body.clientWidth ||
                      document.body.offsetWidth;

    return actualWidth;
}

11
私たちは身長について話している。幅ではありません。
Yash

0

機能検出を使用してオンデマンドでページをスクロールできない場合は、アニメーションハックで使用する機能を検出するためにこのハックを思いつきました。

問題は両方でdocument.body.scrollTopあり、document.documentElement常にtrueすべてのブラウザーで再発しました。

ただし、実際にスクロールできるのはどちらか一方のみです。w3schoolsによるd.body.scrollTopSafariおよびdocument.documentElementその他のすべて(例を参照)

element.scrollTop すべてのブラウザで機能しますが、ドキュメントレベルでは機能しません。

    // get and test orig scroll pos in Saf and similar 
    var ORG = d.body.scrollTop; 

    // increment by 1 pixel
    d.body.scrollTop += 1;

    // get new scroll pos in Saf and similar 
    var NEW = d.body.scrollTop;

    if(ORG == NEW){
        // no change, try scroll up instead
        ORG = d.body.scrollTop;
        d.body.scrollTop -= 1;
        NEW = d.body.scrollTop;

        if(ORG == NEW){
            // still no change, use document.documentElement
            cont = dd;
        } else {
            // we measured movement, use document.body
            cont = d.body;
        }
    } else {
        // we measured movement, use document.body
        cont = d.body;
    }

-1

高さ+スクロールの計算にブローコードを使用する

var dif = document.documentElement.scrollHeight - document.documentElement.clientHeight;

var height = dif + document.documentElement.scrollHeight +"px";

-1

以下のクロスブラウザーコードは、body要素とhtml要素のすべての可能な高さを評価し、見つかった最大値を返します。

            var body = document.body;
            var html = document.documentElement;
            var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight); // The max height of the body

実際の例:

function getHeight()
{
  var body = document.body;
  var html = document.documentElement; 
  var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight);
  return bodyH;
}

document.getElementById('height').innerText = getHeight();
body,html
{
  height: 3000px;
}

#posbtm
{
  bottom: 0;
  position: fixed;
  background-color: Yellow;
}
<div id="posbtm">The max Height of this document is: <span id="height"></span> px</div>

example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />


反対票を投じる場合の動機を説明して、ポイントを訂正します。どうもありがとう
willy wonka

-4

私は今のところ高さを決定することについて知りませんが、これを使って何かを下に置くことができます:

<html>
<head>
<title>CSS bottom test</title>
<style>
.bottom {
  position: absolute;
  bottom: 1em;
  left: 1em;
}
</style>
</head>

<body>

<p>regular body stuff.</p>

<div class='bottom'>on the bottom</div>

</body>
</html>

1
私を信じて、私はこれでHTMLとCSSリソースを使い果たしました。それを説明することはできませんが、これらのサイトでこれを試すと問題が発生します。
ニック

-4

参照を適切に追加する

私の場合、ASCXページを使用しており、ascxコントロールを含むaspxページが参照を正しく使用していません。次のコードを貼り付けたところ、うまくいきました。

<script src="../js/jquery-1.3.2-vsdoc.js" type="text/javascript"></script>
<script src="../js/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../js/jquery-1.5.1.js" type="text/javascript"></script>
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.