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.
(文档大小是浏览器兼容性的噩梦,因为尽管所有浏览器都公开了clientHeight和scrollHeight属性,但是它们并不都同意如何计算值。)
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.(这涉及使用document.documentElement属性(如果可用)或依靠文档属性等。)
The simplest way to get correct height is to get all height values found on document, or documentElement, and use the highest one.
(获取正确高度的最简单方法是获取文档或documentElement上找到的所有高度值,并使用最高的值。)
This is basically what jQuery does:(基本上,这就是jQuery的作用:)
var body = document.body,
html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
A quick test with Firebug + jQuery bookmarklet returns the correct height for both cited pages, and so does the code example.
(使用Firebug + jQuery小书签进行的快速测试将为两个引用的页面返回正确的高度,代码示例也是如此。)
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.
(请注意,在文档准备就绪之前测试文档的高度将始终为0。此外,如果您在其中加载了更多内容,或者用户调整了窗口的大小,则可能需要重新测试。)
Use onload
or a document ready event if you need this at load time, otherwise just test whenever you need the number.(如果需要在加载时使用onload
或文档就绪事件,请在需要该数字时进行测试。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…