如何不使用 jquery 获得文档的高度和宽度

如何获得纯 中的文档高度和宽度,即不使用
我知道 $(document).height()$(document).width(),但是我想在 中做这个。

我是说页面的高度和宽度。

196417 次浏览
var height = document.body.clientHeight;
var width = document.body.clientWidth;

检查: 这篇文章为更好的解释。

你也可以试试:

document.body.offsetHeight
document.body.offsetWidth

甚至在 http://www.howtocreate.co.uk/tutorials/javascript/browserwindow上给出的最后一个例子也不能在 Quirks 模式下工作。比我想象的更容易找到,这似乎就是解决方案(从最新的 jquery 代码中提取) :

Math.max(
document.documentElement["clientWidth"],
document.body["scrollWidth"],
document.documentElement["scrollWidth"],
document.body["offsetWidth"],
document.documentElement["offsetWidth"]
);

只需将 Width 替换为 Height 即可得到 Height。

您应该使用 getBoundingClientRect,因为它通常是 跨浏览器工作,并且在边界矩形上给出 亚像素精度亚像素精度

elem.getBoundingClientRect()

这应该适用于所有浏览器/设备:

function getActualWidth()
{
var actualWidth = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth ||
document.body.offsetWidth;


return actualWidth;
}

如果希望获得页面的全宽度(包括溢出) ,请使用 document.body.scrollWidth

不使用 jQuery 获取文档大小

document.documentElement.clientWidth
document.documentElement.clientHeight

如果你需要屏幕尺寸,请使用这个

screen.width
screen.height

这是一个跨浏览器的解决方案:

var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

如何很容易地找出文档的宽度和高度?

以超文本标示语言(HTML)
<span id="hidden_placer" style="position:absolute;right:0;bottom:0;visibility:hidden;"></span>

在 javascript 中

     var c=document.querySelector('#hidden_placer');


var r=c.getBoundingClientRect();
r.right=document width
r.bottom=document height`

如果需要,您可以在每个窗口大小调整事件中更新此命令。

window是整个浏览器的应用程序窗口。 document是显示的实际加载的网页。

window.innerWidthwindow.innerHeight将考虑滚动条,这可能不是你想要的。

document.documentElement是没有顶部滚动条的完整网页。 document.documentElement.clientWidth返回没有 y 滚动条的文档宽度大小。 document.documentElement.clientHeight返回不带 x 滚动条的文档高度大小。