it-source

JavaScript를 사용하여 문서 전체의 높이를 얻는 방법

criticalcode 2022. 11. 1. 00:00
반응형

JavaScript를 사용하여 문서 전체의 높이를 얻는 방법

문서의 높이를 알 수 없는 문서도 있습니다(무엇을 맨 아래에 배치하기 위해).게다가 의 패딩 보텀은, 이러한 페이지에서는 아무것도 행해지지 않는 것처럼 보이지만, 높이가 돌아오는 페이지에서는 행해집니다.적절한 예:

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


jQuery's$(document).height();합니다.
document.height를 반환하다
document.body.scrollHeight를 반환하다

「 」 「 」 。
jQuery's$(document).height(); " " " " 。$(document)입니다.
document.height됩니다.
document.body.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로드 시 필요한 경우 문서 준비 이벤트 또는 번호가 필요할 때마다 테스트합니다.

이것은 매우 오래된 질문이기 때문에 많은 구식 답변을 가지고 있습니다.2020년 현재 모든 주요 브라우저는 표준을 준수하고 있습니다.

2020년에 대한 답변:

document.body.scrollHeight

을 두지 않다.<body>있다면 을 사용하세요신체에 여백이 있는 경우 다음을 사용합니다.

document.documentElement.scrollHeight

다음 항목도 사용할 수 있습니다.

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

전체 문서 높이 계산:

보다 일반적으로 문서의 높이를 찾으려면 간단한 재귀로 현재 페이지에서 가장 높은 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://paperbackswap.com/) 또는 http://paperbackswap.com/)에서 테스트할 수 있습니다.

메모: 이 파일은Iframes.

맛있게 드세요!

문서 크기를 결정하는 "jQuery method"는 모든 것을 쿼리하고, 가장 높은 값을 취하며, 최상의 결과를 기대하며, 대부분의 경우 작동하지만 모든 경우에 작동하지는 않습니다.

문서 크기에 대한 방탄 결과가 꼭 필요한 경우 jQuery.documentSize 플러그인을 사용하는 것이 좋습니다.다른 방법과는 달리 실제로는 로드 시 브라우저 동작을 테스트하고 평가하며, 그 결과에 따라 이후 올바른 속성을 조회합니다.

이 일회성 테스트가 성능에 미치는 영향은 미미하며, 플러그인은 가장 이상한 시나리오에서도 올바른 결과를 반환합니다.이러한 이유는 제가 말하는 것이 아니라 대규모 자동 생성된 테스트 스위트가 실제로 성능을 검증하기 때문입니다.

플러그인은 바닐라 Javascript로 되어 있기 때문에 jQuery 없이도 사용할 수 있습니다.

거짓말을 했습니다.jQuery는 두 페이지 $(문서)에 대해 올바른 값을 반환합니다.높이();...내가 왜 의심했을까?

2017년의 정답은 다음과 같습니다.

document.documentElement.getBoundingClientRect().height

와는 달리document.body.scrollHeight이 방법은 신체 마진을 설명한다.또한 일부 경우에 유용한 부분 높이 값을 제공합니다.

크로스 브라우저/디바이스 방식으로 너비를 얻으려면 다음을 사용합니다.

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

    return actualWidth;
}

기능 검출을 사용해 온 디맨드로 페이지를 스크롤 할 수 없는 분들을 위해서, 애니메이션 스크롤로 사용하는 기능을 검출하기 위해서, 이 해킹을 생각해 냈습니다.

문제는 둘 다였다.document.body.scrollTop그리고.document.documentElement항상 반환됨true모든 브라우저에서.

그러나 실제로는 둘 중 하나로만 문서를 스크롤할 수 있습니다. d.body.scrollTopSafari 및document.documentElementw3에 따른 기타 모든 것(예 참조)

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

계산 높이 + 스크롤에 블로우 코드 사용

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

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

다음 크로스 브라우저 코드는 본문과 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 />

지금은 높이를 결정할 수 없습니다만, 이것을 사용하여 아래쪽에 무언가를 놓을 수 있습니다.

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

참조를 올바르게 추가하다

제 경우 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>

언급URL : https://stackoverflow.com/questions/1145850/how-to-get-height-of-entire-document-with-javascript

반응형