【问题标题】:Total height of the page页面总高度
【发布时间】:2009-07-06 16:26:37
【问题描述】:

我正在尝试使用 JavaScript 获取页面的总高度,以便我可以检查页面是否足够长以显示某些内容,但是在我的测试中我无法获取页面的总高度。

我在 Internet 上四处查看,但似乎没有很好的文档记录,因为我只能找到 scrollHeight,正如我可能提到的那样,它不起作用。

有什么方法可以使用 JavaScript 找到它吗?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    没有框架:

    var _docHeight = (document.height !== undefined) ? document.height : document.body.offsetHeight;
    var _docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
    

    【讨论】:

    【解决方案2】:

    document.documentElement.scrollHeight 在最新版本的 Internet Explorer、Chrome、Firefox 和 Safari 中对我来说工作正常。

    【讨论】:

    • scrollHeight 将为您提供页面的高度,包括您需要滚动才能看到的内容。 offsetHeight 将为您提供可见窗口内容区域的高度。
    • offsetHeight 不包含边框、边距和内边距。
    • 这个返回值的单位是什么?
    【解决方案3】:

    你试过$(document).height();吗?

    演示here

    【讨论】:

    【解决方案4】:

    整个页面的高度...

    document.body.offsetHeight
    

    视口高度...

    var h,
    de = document.documentElement;
    
    if (self.innerHeight) {h = window.innerHeight;}
    else if (de && de.clientHeight) {h = de.clientHeight;}
    else if (document.body) {h = document.body.clientHeight;}
    

    This article 可以帮到你。

    【讨论】:

      【解决方案5】:

      要找到整个文档的高度,您可以通过简单的递归找到当前页面上最高的 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);
      })();
      

      注意:它与Iframes 一起使用。

      享受吧!

      【讨论】:

        【解决方案6】:

        也许使用页面底部元素的位置,比如:

        $("#footer").offset().top
        

        【讨论】:

          【解决方案7】:

          看看documentation。支持的方法之一:height、innerHeight、outerHeight 可能适合您。

          【讨论】:

            猜你喜欢
            • 2012-10-15
            • 2012-04-15
            • 2013-07-28
            • 2013-03-28
            • 2020-11-07
            • 1970-01-01
            • 2010-11-11
            • 2015-02-09
            • 2012-02-14
            相关资源
            最近更新 更多