我会尽量简单地回答。
文档和视口
在几何方面,有两组尺寸需要注意;文档尺寸,反映加载页面的整个尺寸,包括窗口底部以外的内容和视口尺寸,反映立即显示在窗口中的文档可见部分的尺寸。
向下滚动时,视口在文档上向下移动一定数量的像素。换句话说,视口是实际的浏览器窗口“边框”(工具栏、菜单、选项卡等)。
造成混乱的原因在于,根据浏览器和模式,使用不同的属性来获取文档和视口的尺寸,并且根据滚动条返回不同的结果。但我们会回到这个话题。
尺寸概览
javascript 中从一开始就有许多可用的属性,它们为您提供了不同的维度。
屏幕分辨率:window.screen.width -Height
可用屏幕空间(与显示器分辨率相同)减去底座、工具栏和其他 UI 元素:window.screen.availWidth -Height
.
文件尺寸:document.documentElement.offsetWidth -Height
注意:这些数字不包括滚动条。
-
视口尺寸:window.innerWidth -Height
关于文档尺寸的注释
如上所述,document.documentElement.offsetWidth/Height
为您提供文档的实际大小。需要注意的是,滚动条在浏览器之间的工作方式不同。例如,即使文档高度小于视口高度,IE9也会始终显示垂直滚动条。 Safari/Chrome 在 OS X Lion 上没有滚动条。除非需要,PC 上的 Chrome 不会显示垂直滚动条。
所以你可能会遇到不一致的情况滚动条移动内容问题。想象一下您有一个绝对定位且居中的元素。因为 CSS 计算的是相对于文档尺寸而不是视口尺寸的“中心”,所以当 Google 添加滚动条时,您的内容可能会随着“文档中心”的变化而向左“跳跃”一点。因此,如果您感到困扰,您可能需要编写 JS 来补偿这种影响,或者也许这里有人可以编写一个快速的 JS 函数来计算包含滚动条的文档尺寸。
滚动条位置和尺寸
虽然 JavaScript 中的某些方法使用文档坐标,但其他方法使用视口坐标,而这通常不是您想要的。例如,如果元素的上边缘位于文档坐标中的 20 像素处,并且将页面向下滚动 20 像素,则该元素的上边缘将位于相对于顶部视口坐标的 0 像素处。因此,要在两个系统之间进行转换,您首先需要知道用户滚动了文档的像素数,然后将该数字添加到视口中进行补偿(请参见下面的示例)。
我还发现这些很有帮助:
http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
http://www.quirksmode.org/mobile/viewports.html
这是我搞砸的一个快速跨浏览器模块来帮助你:
var dimensions = (function(){
var dims = {};
// get screen width/height:
dims.screenWidth = function() { window.screen.width };
dims.screenHeight = function() { return window.screen.height };
// get screen width/height minus chrome:
dims.availWidth = function() { return window.screen.availWidth };
dims.availHeight = function() { return window.screen.availHeight };
// get document width/height (with-out scrollbars):
if (window.document.compatMode == "CSS1Compat"){ // if IE Standards Mode
dims.documentWidth = function() { return document.body.offsetWidth };
dims.documentHeight = function() { return document.body.offsetHeight };
}
else {
dims.documentWidth = function() { return document.documentElement.offsetWidth };
dims.documentHeight = function() { return document.documentElement.offsetHeight };
}
// get viewport width/height (with scrollbars):
if (window.innerWidth != null) {
dims.viewportWidth = function () { return window.innerWidth };
dims.viewportHeight = function () { return window.innerHeight };
}
// if IE in Standards Mode
else if (window.document.compatMode == "CSS1Compat"){
dims.viewportWidth = function () {
return window.document.documentElement.clientWidth
};
dims.viewportHeight = function () {
return window.document.documentElement.clientHeight
};
}
// get scrollbar offsets:
if (window.pageXOffset != null) {
dims.scrollXOffset = function() { return window.pageXOffset };
dims.scrollYOffset = function() { return window.pageYOffset };
}
// if IE in Standards Mode
else if (window.document.compatMode == "CSS1Compat"){
dims.scrollXOffset = function() { return document.documentElement.scrollLeft };
dims.scrollYOffset = function() { return document.documentElement.scrollTop };
}
return dims;
}());
例如,你可以这样做console.log(dimensions.viewportWidth())
获取视口宽度。
希望这对您有帮助:)