如何用JavaScript获取整个文档的高度? [英] How to get height of entire document with JavaScript?
问题描述
有些文件我无法获得文件的高度(绝对位于最底层)。此外,填充底部似乎在这些页面上什么也不做,但在高度将返回的页面上执行。案例:
Some documents I can't get the height of the document (to position something absolutely at the very bottom). Additionally, a padding-bottom on seems to do nothing on these pages, but do on the pages where height will return. Case(s) in point:
http://fandango.com
http://paperbackswap.com
On Fandango
jQuery的 $(文件).height();
返回正确的值
document.height
返回0
document.body.scrollHeight
返回0
On Fandango
jQuery's $(document).height();
returns correct value
document.height
returns 0
document.body.scrollHeight
returns 0
On Bookback Swap:
jQuery的 $(文件).height();
TypeError: $(文件)
为空
document.height
返回不正确的值
document.body.scrollHeight
返回不正确的值
On Paperback Swap:
jQuery's $(document).height();
TypeError: $(document)
is null
document.height
returns an incorrect value
document.body.scrollHeight
returns an incorrect value
注意:如果有一些技巧,我有浏览器级权限。
Note: I have browser level permissions, if there is some trick there.
推荐答案
文档尺寸是一个浏览器兼容性恶梦,因为尽管所有浏览器暴露clientHeight和scrollHeight属性的属性,它们不都同意如何值的重新计算。
Document sizes are a browser compatibility nightmare because, although all browsers expose clientHeight and scrollHeight properties, they don't all agree how the values are calculated.
对于如何测试正确的高度/宽度,过去有一个复杂的最佳实践公式。这涉及使用document.documentElement属性(如果可用)或回退到文档属性等。
There used to be a complex best-practice formula around for how you tested for correct height/width. This involved using document.documentElement properties if available or falling back on document properties and so on.
获得正确高度的最简单方法是获取文档或documentElement上的所有高度值,并使用最高的值。这基本上就是jQuery的作用:
The simplest way to get correct height is to get all height values found on document, or documentElement, and use the highest one. This is basically what jQuery does:
var body = document.body,
html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
使用Firebug进行快速测试+ jQuery bookmarklet 返回两个引用页面的正确高度,代码示例也是如此。
A quick test with Firebug + jQuery bookmarklet returns the correct height for both cited pages, and so does the code example.
请注意,在文档准备好之前测试文档的高度将始终为0.此外,如果您加载更多内容,或者用户调整窗口大小,您可能需要重新测试。如果您需要,请使用 onload
或文档就绪活动在加载时,否则只需在需要时测试。
Note that testing the height of the document before the document is ready will always result in a 0. Also, if you load more stuff in, or the user resizes the window, you may need to re-test. Use onload
or a document ready event if you need this at load time, otherwise just test whenever you need the number.
这篇关于如何用JavaScript获取整个文档的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!