关于body.clientHeight,body.clientWidht获取的不是可视高度的问题

我发现网上一些教程可能都是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:

  1. If the element has no associated CSS layout box or if the CSS layout box is inline, return zero.
  2. 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).
  3. 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属性必须运行以下步骤:

  1. 如果元素没有关联的CSS 布局框或者CSS 布局框是内联的,则返回零。
  2. 如果元素是根元素并且元素的节点文档不是quirks 模式,或者如果元素是HTMLbody元素并且元素的节点文档 是quirks 模式,则返回不包括渲染滚动条大小的视口高度(如果有)。
  3. 返回填充边缘的高度,不包括填充边缘和边框边缘之间的任何渲染滚动条的高度,忽略应用于元素及其祖先的任何变换。

第2条就明确提到元素是根元素并且不是quirks mode,或者元素是body并且是quirks mode。使用clientHeight才能正确获取可视窗口的高度

参考链接
Java Script 标准参考教程 Element.clientHeight,Element.clientWidth

mdn web docs Element.clientHeight

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值