javascript - window.innerWidth 与 document.documentElement.clientWidth

标签 javascript html dom standards w3c

关于window.innerWidthdocument.documentElement.clientWidth

  1. Webkit (Chrome/Safari) 声明 innerWidth 小于 clientWidth

  2. Trident 和 Presto 声称 innerWidth 大于 clientWidth

  3. Gecko 声称 innerWidthclientWidth 大小相同。

W3C(或类似的“权威”)声明正确行为是什么?

测试脚本(on JSFiddle)(在 GoogleHost 上):

setInterval(function() {
  var inner_w = window.innerWidth;
  var inner_h = window.innerHeight;
  var client_w = document.documentElement.clientWidth;
  var client_h = document.documentElement.clientHeight;
  var debug_msg = "inner: " + inner_w + "-" + inner_h + "<br>client: " + client_w + "-" + client_h;
  document.getElementById("d").innerHTML = debug_msg;
  document.title = debug_msg;
  document.body.style.background = (client_w === inner_w && client_h === inner_h ? "green" : "red");
}, 60);
<div id="d"></div>

(以全页模式运行代码段并取消最大化或“恢复”窗口。在拖动窗口边缘以调整其大小的同时观察debug_msg。)

最佳答案

根据 W3C specification (2016 年 3 月 17 日):

The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any), or zero if there is no viewport.

...

The clientWidth 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 document is not in quirks mode, or if the element is the HTML body element and the element's document is in quirks mode, return the viewport width excluding the size of a rendered scroll bar (if any).
  3. Return the width of the padding edge excluding the width of any rendered scrollbar between the padding edge and the border edge, ignoring any transforms that apply to the element and its ancestors.

关于javascript - window.innerWidth 与 document.documentElement.clientWidth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6942785/

相关文章:

javascript - 部分 View 中不显眼的客户端验证不起作用

html - 如何将右栏(桌面)分成两部分,一个显示在手机顶部,另一个显示在底部?

javascript - 我可以保留对文档片段的引用吗?

javascript - 将内部 div 文本传递给函数

javascript - Plupload 问题 - 正在使用 {Filename}.part 上传文件且未触发 FileUploadedevent

javascript - 在 JavaScript 中使用正则表达式来检查模式重用(例如,在字符串中声明两次的相同字符序列)

HTML5 链接到部分

javascript - 将页面 anchor 传递到新页面而不使用 URL

jquery - 在 DOM 上可视化地交换两个 HTML 元素,然后将其全部动画化?

javascript - 当文件作为 'Error' 发送时,Express Route 返回状态代码 500 和通用 'multipart/form-data'