我发现网上一些教程可能都是10几年前的老古董了,经过不知道多少号复制翻新,导致有时候你很难去发现问题,甚至是大部分的教程都是这么写的,害人不浅。
问题的经过是这样的,我需要获取页面的可视高度。网上搜一搜,全部都说使用body.clientHeight来获取,结果嘛获取的是body的总高度
经过我一番查找,发现问题所在。body.clientHeight
只有在quirks mode(怪异模式)
下才能返回可视高度,在strict mode(标准模式)
要使用的是根节点的clientHeight,也就是 document.documentElement.clientHeight
。
所谓标准模式的判定是你在HTML文件上方声明了<!DOCTYPE html>
.
以下是 w3c Extensions to the Element Interface的原文:
The clientHeight attribute must run these steps:
- If the element has no associated CSS layout box or if the CSS layout box is inline, return zero.
- If the element is the root element and the element’s node document is not in quirks mode, or if the element is the HTML body element and
the element’s node document is in quirks mode, return the viewport
height excluding the size of a rendered scroll bar (if any).- Return the height of the padding edge excluding the height of any rendered scrollbar between the padding edge and the border edge,
ignoring any transforms that apply to the element and its ancestors.
中文翻译如下:
clientHeight属性必须运行以下步骤:
- 如果元素没有关联的CSS 布局框或者CSS 布局框是内联的,则返回零。
- 如果元素是根元素并且元素的节点文档不是quirks 模式,或者如果元素是HTMLbody元素并且元素的节点文档 是quirks 模式,则返回不包括渲染滚动条大小的视口高度(如果有)。
- 返回填充边缘的高度,不包括填充边缘和边框边缘之间的任何渲染滚动条的高度,忽略应用于元素及其祖先的任何变换。
第2条就明确提到元素是根元素并且不是quirks mode,或者元素是body并且是quirks mode。使用clientHeight才能正确获取可视窗口的高度
参考链接:
Java Script 标准参考教程 Element.clientHeight,Element.clientWidth