如何获取windowWidth、windowHeight、pageWidth、pageHeight、screenWidth、screenHeight、pageX、pageY、screenX、screenY,这些都可以在所有主要浏览器中使用?


当前回答

这有您需要知道的一切:获取视口/窗口大小

但简而言之:

var win = window,
    doc = document,
    docElem = doc.documentElement,
    body = doc.getElementsByTagName('body')[0],
    x = win.innerWidth || docElem.clientWidth || body.clientWidth,
    y = win.innerHeight|| docElem.clientHeight|| body.clientHeight;
alert(x + ' × ' + y);

不停摆弄

请停止编辑此答案。它已经被不同的人编辑了22次,以符合他们的代码格式偏好。也有人指出,如果你只想瞄准现代浏览器,这是不需要的——如果是的话,你只需要以下内容:

const width  = window.innerWidth || document.documentElement.clientWidth || 
document.body.clientWidth;
const height = window.innerHeight|| document.documentElement.clientHeight|| 
document.body.clientHeight;

console.log(width, height);

其他回答

如果您需要一个真正防弹的文档宽度和高度解决方案(图片中的pageWidth和pageHeight),您可能需要考虑使用我的插件jQuery.documentSize。

它只有一个目的:即使在jQuery和其他方法失败的情况下,也始终返回正确的文档大小。尽管有jQuery的名字,但您不必使用它——它是用普通的Javascript编写的,也可以在没有jQuery的情况下使用。

用法:

var w = $.documentWidth(),
    h = $.documentHeight();

用于全局文档。对于其他文档,例如在您有权访问的嵌入式iframe中,将文档作为参数传递:

var w = $.documentWidth( myIframe.contentDocument ),
    h = $.documentHeight( myIframe.contentDocument );

更新:现在也更新窗口尺寸

从1.1.0版开始,jQuery.documentSize还处理窗口维度。

这是必要的,因为

$(window).height()在iOS中有缺陷,以至于没有用$(window).width()和$(window).height()在移动设备上不可靠,因为它们无法处理移动缩放的效果。

jQuery.documentSize提供了$.windowWidth()和$.windowHeight()来解决这些问题。有关更多信息,请查看文档。

使用“控制台”或单击“检查”后,检查任何网站当前加载页面的高度和宽度。

步骤1:单击鼠标右键,单击“检查”,然后单击“控制台”

步骤2:确保您的浏览器屏幕不应处于“最大化”模式。如果浏览器屏幕处于“最大化”模式,您需要首先单击最大化按钮(位于右上角或左上角),然后取消最大化。

步骤3:现在,在大于号('>')后面写以下内容,即。

       > window.innerWidth
            output : your present window width in px (say 749)

       > window.innerHeight
            output : your present window height in px (say 359)

您可以使用jQuery获取窗口或文档的大小:

// Size of browser viewport.
$(window).height();
$(window).width();

// Size of HTML document (same as pageHeight/pageWidth in screenshot).
$(document).height();
$(document).width();

对于屏幕大小,可以使用屏幕对象:

window.screen.height;
window.screen.width;

获取可用屏幕维度的非jQuery方法。window.screen.width/height已经发布,但为了响应Web设计和完整性,我认为值得提及这些属性:

alert(window.screen.availWidth);
alert(window.screen.availHeight);

http://www.quirksmode.org/dom/w3c_cssom.html#t10 :

availWidth和availHeight-屏幕(不包括OS任务栏等)。

您可以使用Screen对象获取此信息。

以下是它将返回的内容的示例:

Screen {
    availWidth: 1920,
    availHeight: 1040,
    width: 1920,
    height: 1080,
    colorDepth: 24,
    pixelDepth: 24,
    top: 414,
    left: 1920,
    availTop: 414,
    availLeft: 1920
}

要获得screenWidth变量,只需使用screen.width,与screenHeight相同,只需选择screen.height。

要获取窗口宽度和高度,请分别为screen.availWidth或screen.avail height。

对于pageX和pageY变量,请使用window.screenX或Y。请注意,这是从非常左/最左/最上的屏幕开始的。因此,如果您有两个宽度为1920的屏幕,那么右屏幕左侧500px的窗口的X值将为2420(1920+500)。然而,screen.width/height显示当前屏幕的宽度或高度。

要获取页面的宽度和高度,请使用jQuery的$(window).height()或$(window).width()。

再次使用jQuery,为pageX和pageY值使用$(“html”).offset().top和$(“html”).ooffset().left。