【发布时间】:2009-07-06 16:26:37
【问题描述】:
我正在尝试使用 JavaScript 获取页面的总高度,以便我可以检查页面是否足够长以显示某些内容,但是在我的测试中我无法获取页面的总高度。
我在 Internet 上四处查看,但似乎没有很好的文档记录,因为我只能找到 scrollHeight,正如我可能提到的那样,它不起作用。
有什么方法可以使用 JavaScript 找到它吗?
【问题讨论】:
标签: javascript
我正在尝试使用 JavaScript 获取页面的总高度,以便我可以检查页面是否足够长以显示某些内容,但是在我的测试中我无法获取页面的总高度。
我在 Internet 上四处查看,但似乎没有很好的文档记录,因为我只能找到 scrollHeight,正如我可能提到的那样,它不起作用。
有什么方法可以使用 JavaScript 找到它吗?
【问题讨论】:
标签: javascript
没有框架:
var _docHeight = (document.height !== undefined) ? document.height : document.body.offsetHeight;
var _docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
【讨论】:
document.documentElement.scrollHeight 在最新版本的 Internet Explorer、Chrome、Firefox 和 Safari 中对我来说工作正常。
【讨论】:
offsetHeight 不包含边框、边距和内边距。
你试过$(document).height();吗?
演示here
【讨论】:
document.body.clientHeight。见:developer.mozilla.org/en-US/docs/Web/API/Document/height
整个页面的高度...
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 可以帮到你。
【讨论】:
要找到整个文档的高度,您可以通过简单的递归找到当前页面上最高的 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 一起使用。
享受吧!
【讨论】:
也许使用页面底部元素的位置,比如:
$("#footer").offset().top
【讨论】:
看看documentation。支持的方法之一:height、innerHeight、outerHeight 可能适合您。
【讨论】: