【问题标题】:How to get height of entire document with JavaScript?如何使用 JavaScript 获取整个文档的高度?
【发布时间】:2010-11-11 20:44:03
【问题描述】:

某些文档我无法获得文档的高度(将某些东西绝对定位在最底部)。此外,padding-bottom on 似乎在这些页面上没有任何作用,但在高度将返回的页面上起作用。案例:

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

在范丹戈
jQuery 的 $(document).height(); 返回正确值
document.height 返回 0
document.body.scrollHeight 返回 0

关于平装书交换:
jQuery 的 $(document).height(); TypeError: $(document) is null
document.height 返回一个不正确的值
document.body.scrollHeight 返回一个不正确的值

注意:我有浏览器级别的权限,如果那里有什么技巧的话。

【问题讨论】:

  • $(document) 为空,因为该站点没有加载 jQuery...
  • 嗯,我可以发誓我检查了其他东西以确认 jQuery 已注册,但它看起来不像我那样做,哈!我以为firebug已经打包了jQuery......嗯,我想我会检查一下,如果它是一个解决方案。
  • firebug 没有 jQUery 打包
  • Finding the size of the browser window。它有一个很好的不同浏览器行为的表格。

标签: javascript


【解决方案1】:

文档大小是浏览器兼容性的噩梦,因为尽管所有浏览器都公开了 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 bookmarklet 进行快速测试会返回两个引用页面的正确高度,代码示例也是如此。

请注意,在文档准备好之前测试文档的高度总是会导致 0。此外,如果您加载了更多内容,或者用户调整了窗口大小,您可能需要重新测试。如果您在加载时需要此事件,请使用 onloaddocument ready 事件,否则只需在需要数字时进行测试。

【讨论】:

  • 评价这个解决方案,因为它在您使用原型库时有效,使用 jQuery 则没有这样的问题
  • 使用 iframe 和 jquery 时,由于这种计算方法,iframe 的文档高度总是至少是 iframe 本身的高度。当您想减小 iframe 的高度以匹配内容时,请务必注意这一点。您首先必须重置 iframe 的高度。
  • 我需要扩大 iframe 并缩小它(facebook 应用程序),发现 document.body.offsetHeight 是我的最佳选择,大多数浏览器都准确支持。
  • 这很好,虽然如果文档没有准备好会给出不正确的结果 - 即,在服务器生成的代码中使用时......
  • 在文档准备好之前对其进行测试是行不通的。这与生成的代码/文档无关,而是与文档的加载方式无关。测试必须在文档准备好之后运行,我建议仅在文档完全加载时运行它,因为剩余项目可能会影响高度,也会影响浏览器的大小。
【解决方案2】:

这是一个非常古老的问题,因此有许多过时的答案。截至 2020 年,所有 major browsers have adhered to the standard.

2020 年的答案:

document.body.scrollHeight

编辑:上面没有考虑<body> 标签的边距。如果您的身体有边距,请使用:

document.documentElement.scrollHeight

【讨论】:

  • 截至 2017 年,这应该被标记为我的正确答案。
  • @Joan 这取决于原始发布者:)
  • 在存在边距时不起作用。 document.documentElement.getBoundingClientRect() 效果更好。
  • 这里有一个错误:例如,在<body> 的开头有一个<h1> 元素,它的默认边距,它会将<body> 元素向下推而没有检测它的方法。 document.documentElement.scrollHeight(不是document.body,scrollHeight)是最准确的做事方式。这适用于身体边缘和身体内部将其向下推的东西的边缘。
【解决方案3】:

你甚至可以使用这个:

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

【讨论】:

    【解决方案4】:

    完整文档高度计算:

    为了更通用并找到任何文档的高度,您可以通过简单的递归找到当前页面上最高的 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);
    })();
    

    您可以在示例网站(http://fandango.com/http://paperbackswap.com/)上测试它,并将此脚本粘贴到 DevTools 控制台。

    注意:它与 Iframes 一起使用。

    享受吧!

    【讨论】:

    • 这就像一个魅力!这里没有其他答案可以获取完整高度(包括可滚动区域),它们都只返回可见区域的高度。
    • 真的很特别,从来没想过。我想只有一个在 phantomjs 工作。
    【解决方案5】:

    确定文档大小的“jQuery 方法”——查询所有内容,取最高值,并希望最好——在大多数情况下都有效,但not in all of them

    如果您真的需要文档大小的防弹结果,我建议您使用我的jQuery.documentSize 插件。与其他方法不同,它实际上在加载时测试和评估浏览器行为,并根据结果从那里查询正确的属性。

    这种一次性测试对性能的影响is minimal,即使在最奇怪的情况下,插件也会返回正确的结果 - 不是因为我这么说,而是因为一个庞大的自动生成的测试套件实际上可以验证它可以。

    因为插件是用原生 Javascript 编写的,所以你也可以使用它without jQuery

    【讨论】:

      【解决方案6】:

      我撒谎了,jQuery 为两个页面返回了正确的值 $(document).height();...为什么我曾经怀疑过它?

      【讨论】:

      • 不同的浏览器兄弟。
      【解决方案7】:

      2017 年的正确答案是:

      document.documentElement.getBoundingClientRect().height

      document.body.scrollHeight 不同,此方法考虑正文边距。 它还提供分数高度值,在某些情况下可能很有用

      【讨论】:

      • 这些是我在此页面上尝试您的方法时得到的结果:i.imgur.com/0psVkIk.png 您的方法返回看起来像窗口高度的东西,而document.body.scrollHeight 列出了整个可滚动高度,这就是提出的原始问题。
      • @Marquizzo 那是因为这个页面在 css 中有html { height: 100% }。因此 API 正确地返回 real 计算的高度。尝试删除此样式并为body 添加边距,您将看到使用document.body.scrollHeight 有什么问题。
      • 这里有一个错误:例如,在<body> 的开头有一个<h1> 元素,它的默认边距,它会将<body> 元素向下推而没有检测它的方法。 document.documentElement.scrollHeight(不是document.body,scrollHeight)是最准确的做事方式。
      • @Booligoosh 不确定您的意思。 documentElement.scrollHeight 在这种情况下给出了错误的值。 documentElement.getBoundingClientRect().height 给出了正确的答案。看看这个:jsfiddle.net/fLpqjsxd
      • @torvin 事实上,getBoundingClientRect().height 没有返回预期的结果。它会偏离轨道,而其他 3(三)种方法不会偏离轨道。包括你提到的不如它的那个。您坚持这样做,建议从该页面的 html 高度中删除 100%,并为其添加边距。重点是什么 ?只要接受getBoundingClientRect().height 也不是防弹的。
      【解决方案8】:

      要以跨浏览器/设备的方式获取宽度,请使用:

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

      【讨论】:

      • 我们在谈论身高。不是宽度。
      【解决方案9】:

      对于任何在按需滚动页面时遇到问题的人,使用特征检测,我想出了这个技巧来检测在动画滚动中使用哪个特征。

      问题是document.body.scrollTopdocument.documentElement 在所有浏览器中总是返回true

      但是,您实际上只能使用其中一个滚动文档。 d.body.scrollTop 用于 Safari,document.documentElement 用于所有其他根据 w3schools (see examples)

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

      【讨论】:

        【解决方案10】:

        使用 Blow 代码计算高度 + 滚动

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

        【讨论】:

          【解决方案11】:

          下面的跨浏览器代码评估 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 />

          【讨论】:

          • 请说明投票反对的动机,以便我纠正这一点。非常感谢
          【解决方案12】:

          我现在不知道确定高度,但是你可以用它在底部放一些东西:

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

          【讨论】:

          • 相信我,我已经用尽了 HTML 和 CSS 资源。无法解释,但如果您在这些网站上尝试,您会发现问题。
          【解决方案13】:

          正确添加引用

          就我而言,我使用的是 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>
          

          【讨论】:

            猜你喜欢
            • 2023-04-02
            • 2020-01-25
            • 1970-01-01
            • 1970-01-01
            • 2018-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-03-22
            • 1970-01-01
            相关资源
            最近更新 更多