关于javascript:获取屏幕大小,当前网页和浏览器窗口

Get the size of the screen, current web page and browser window

我怎样才能得到可以在所有主要浏览器中使用的windowWidthwindowHeightpageWidthpageHeightscreenWidthscreenHeightpageXpageYscreenXscreenY

screenshot describing which values are wanted


如果使用jquery,则可以使用jquery方法获取窗口或文档的大小:

1
2
3
4
$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document (same as pageHeight in screenshot)
$(window).width();   // returns width of browser viewport
$(document).width(); // returns width of HTML document (same as pageWidth in screenshot)

对于屏幕大小,可以按以下方式使用screen对象:

1
2
screen.height;
screen.width;


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

但简而言之:

1
2
3
4
5
6
7
var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    x = w.innerWidth || e.clientWidth || g.clientWidth,
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;
alert(x + ' × ' + y);

小提琴


下面是一个带有纯javascript的跨浏览器解决方案(源代码):

1
2
3
4
5
6
7
var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;


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

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

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

availWidth and availHeight - The available width and height on the
screen (excluding OS taskbars and such).


但是当我们谈论响应屏幕时,如果我们出于某种原因想使用jquery来处理它,

1
window.innerWidth, window.innerHeight

给出正确的测量值。即使它删除了滚动条的额外空间,我们也不必担心调整该空间:)


To check height and width of your current loaded page of any website using"console" or after clicking"Inspect".

step 1: Click the right button of mouse and click on 'Inspect' and then click 'console'

step 2: Make sure that your browser screen should be not in 'maximize' mode. If the browser screen is in 'maximize' mode, you need to first click the maximize button (present either at right or left top corner) and un-maximize it.

step 3: Now, write the following after the greater than sign ('>') i.e.

1
2
3
4
5
       > window.innerWidth
            output : your present window width in px (say 749)

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function wndsize(){
  var w = 0;var h = 0;
  //IE
  if(!window.innerWidth){
    if(!(document.documentElement.clientWidth == 0)){
      //strict mode
      w = document.documentElement.clientWidth;h = document.documentElement.clientHeight;
    } else{
      //quirks mode
      w = document.body.clientWidth;h = document.body.clientHeight;
    }
  } else {
    //w3c
    w = window.innerWidth;h = window.innerHeight;
  }
  return {width:w,height:h};
}
function wndcent(){
  var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
  var _x = 0;var _y = 0;var offsetX = 0;var offsetY = 0;
  //IE
  if(!window.pageYOffset){
    //strict mode
    if(!(document.documentElement.scrollTop == 0)){offsetY = document.documentElement.scrollTop;offsetX = document.documentElement.scrollLeft;}
    //quirks mode
    else{offsetY = document.body.scrollTop;offsetX = document.body.scrollLeft;}}
    //w3c
    else{offsetX = window.pageXOffset;offsetY = window.pageYOffset;}_x = ((wndsize().width-hWnd.width)/2)+offsetX;_y = ((wndsize().height-hWnd.height)/2)+offsetY;
    return{x:_x,y:_y};
}
var center = wndcent({width:350,height:350});
document.write(center.x+';');
document.write(center.y+';');
document.write('<DIV align="center" id="rich_ad" style="Z-INDEX: 10; left:'+center.x+'px;WIDTH: 350px; POSITION: absolute; TOP: '+center.y+'px; HEIGHT: 350px"><!--К сожалению, у Вас не установлен flash плеер.-->');

您还可以获得窗口的宽度和高度,避免使用浏览器工具栏和其他东西。它是浏览器窗口中的真正可用区域。

为此,请使用:window.innerWidthwindow.innerHeight属性(见W3Schools的Doc)。

在大多数情况下,这是最好的方式,例如,显示一个完全居中的浮动模式对话框。它允许您计算窗口上的位置,无论使用的是哪个分辨率方向或窗口大小。


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

它只有一个目的:总是返回正确的文档大小,即使在jquery和其他方法失败的情况下也是如此。尽管它的名字,但您不必使用jquery——它是用普通的javascript编写的,并且在没有jquery的情况下也可以工作。

用途:

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

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

1
2
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()来解决这些问题。有关更多信息,请查看文档。


我写了一个小的javascript书签,你可以用它来显示大小。您可以很容易地将其添加到浏览器中,单击它时,您将在浏览器窗口的右角看到大小。

你可以在这里找到如何使用书签的信息。https://en.wikipedia.org/wiki/bookmarklet网站

小书签

1
2
3
javascript:(function(){!function(){var i,n,e;return n=function(){var n,e,t;return t="background-color:azure; padding:1rem; position:fixed; right: 0; z-index:9999; font-size: 1.2rem;",n=i(''),e=function(){return'<p style="margin:0;">width: '+i(window).width()+" height:"+i(window).height()+"
</p>
<hr><P>在某些与响应布局相关的情况下,<wyn>$(document).height()</wyn>可能返回只显示视图端口高度的错误数据。例如,当某个DIV包装器的高度为100%时,该包装器可以被其内部的某个块拉伸。但它的高度仍然和视区高度一样。在这种情况下,你可能会使用</P>[cc lang="
javascript"]$('#wrapper').get(0).scrollHeight

它表示包装器的实际大小。


I developed a library for knowing the real viewport size for desktops and mobiles browsers, because viewport sizes are inconsistents across devices and cannot rely on all the answers of that post (according to all the research I made about this) : https://github.com/pyrsmk/W


有时您需要在调整窗口和内部内容的大小时看到宽度/高度的变化。

为此,我编写了一个小脚本,它添加了一个日志框,动态地监视所有的大小调整和几乎立即更新。

它添加了一个具有固定位置和高z索引的有效HTML,但足够小,因此您可以:

  • 在实际网站上使用
  • 使用它测试移动/响应意见

测试对象:Chrome40、IE11,但也很可能在其他/旧版本的浏览器上工作…:)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  function gebID(id){ return document.getElementById(id); }
  function gebTN(tagName, parentEl){
     if( typeof parentEl =="undefined" ) var parentEl = document;
     return parentEl.getElementsByTagName(tagName);
  }
  function setStyleToTags(parentEl, tagName, styleString){
    var tags = gebTN(tagName, parentEl);
    for( var i = 0; i<tags.length; i++ ) tags[i].setAttribute('style', styleString);
  }
  function testSizes(){
    gebID( 'screen.Width' ).innerHTML = screen.width;
    gebID( 'screen.Height' ).innerHTML = screen.height;

    gebID( 'window.Width' ).innerHTML = window.innerWidth;
    gebID( 'window.Height' ).innerHTML = window.innerHeight;

    gebID( 'documentElement.Width' ).innerHTML = document.documentElement.clientWidth;
    gebID( 'documentElement.Height' ).innerHTML = document.documentElement.clientHeight;

    gebID( 'body.Width' ).innerHTML = gebTN("body")[0].clientWidth;
    gebID( 'body.Height' ).innerHTML = gebTN("body")[0].clientHeight;  
  }

  var table = document.createElement('table');
  table.innerHTML =
      "<tr><th>SOURCE</th><th>WIDTH</th><th>x</th><th>HEIGHT</th></tr>"
      +"<tr><td>screen</td><td id='screen.Width' /><td>x</td><td id='screen.Height' /></tr>"
      +"<tr><td>window</td><td id='window.Width' /><td>x</td><td id='window.Height' /></tr>"
      +"<tr><td>document.documentElement</td><td id='documentElement.Width' /><td>x</td><td id='documentElement.Height' /></tr>"
      +"<tr><td>document.body</td><td id='body.Width' /><td>x</td><td id='body.Height' /></tr>"
  ;

  gebTN("body")[0].appendChild( table );

  table.setAttribute(
     'style',
    "border: 2px solid black !important; position: fixed !important;"
     +"left: 50% !important; top: 0px !important; padding:10px !important;"
     +"width: 150px !important; font-size:18px; !important"
     +"white-space: pre !important; font-family: monospace !important;"
     +"z-index: 9999 !important;background: white !important;"
  );
  setStyleToTags(table,"td","color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");
  setStyleToTags(table,"th","color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");

  table.style.setProperty( 'margin-left', '-'+( table.clientWidth / 2 )+'px' );

  setInterval( testSizes, 200 );

编辑:现在样式只应用于logger table元素-而不是所有表-这也是一个jquery自由解决方案:)


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

下面是它将返回的示例:

1
2
3
4
5
6
7
8
9
10
11
12
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.availWidthscreen.availHeight

对于pageXpageY变量,使用window.screenX or Y。请注意,这是从左/上EST屏幕的左/上。因此,如果你有两个宽度为1920的屏幕,那么从右屏幕左边的500px窗口的x值将为2420(1920+500)。但是,screen.width/height显示当前屏幕的宽度或高度。

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

再次使用jquery,将$("html").offset().top$("html").offset().left用于您的pageXpageY值。


这是我的解决方案!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// innerWidth
const screen_viewport_inner = () => {
    let w = window,
        i = `inner`;
    if (!(`innerWidth` in window)) {
        i = `client`;
        w = document.documentElement || document.body;
    }
    return {
        width: w[`${i}Width`],
        height: w[`${i}Height`]
    }
};


// outerWidth
const screen_viewport_outer = () => {
    let w = window,
        o = `outer`;
    if (!(`outerWidth` in window)) {
        o = `client`;
        w = document.documentElement || document.body;
    }
    return {
        width: w[`${o}Width`],
        height: w[`${o}Height`]
    }
};

// style
const console_color = `
    color: rgba(0,255,0,0.7);
    font-size: 1.5rem;
    border: 1px solid red;
`;



// testing
const test = () => {
    let i_obj = screen_viewport_inner();
    console.log(`%c screen_viewport_inner =
`, console_color, JSON.stringify(i_obj, null, 4));
    let o_obj = screen_viewport_outer();
    console.log(`%c screen_viewport_outer =
`, console_color, JSON.stringify(o_obj, null, 4));
};

// IIFE
(() => {
    test();
})();


我们现在可以在所有浏览器中安全地单独使用本机JavaScript窗口API,而不需要窗口上下文。

语法有点清楚!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
n ="px"  /* separator */
dp = devicePixelRatio /* device zoom level */
body = (() => { document.body.innerHTML = /* ready! */


      "Device zoom level:" +                         dp
+n+   "Screen width:" +                    screen.width
*dp+n+"Screen height:"+                   screen.height
*dp+n+"Document frame height:" +            innerHeight
*dp+n+"Document frame width:" +              innerWidth                             *dp+n+"Parent document height:"+            outerHeight                            *dp+n+"Parent document width:"+              outerWidth                             *dp+n+"Window available height:"+    screen.availHeight                     *dp+n+"Window available width:"+      screen.availWidth                      *dp+n+"Document frame max scrollable X:"+    scrollMaxX                             *dp+n+"Document frame max scrollable Y:"+    scrollMaxY
*dp+n+"Distance from left screen to window:"+   screenX
*dp+n+"Distance from top screen to window:"+    screenY
*dp+n    

})()

为了在每个浏览器和设备中获得准确的结果,结果必须乘以device像素比。

The Window property devicePixelRatio returns the ratio of the
resolution in physical pixels to the resolution in CSS pixels for the
current display device. This value could also be interpreted as the
ratio of pixel sizes: the size of one CSS pixel to the size of one
physical pixel. In simpler terms, this tells the browser how many of
the screen's actual pixels should be used to draw a single CSS pixel.

This is useful when dealing with the difference between rendering on a
standard display versus a HiDPI or Retina display, which use more
screen pixels to draw the same objects, resulting in a sharper image.

There is no way to be notified when this value is changed (which can
happen, for example, if the user drags the window to a display with a
different pixel density). Since there are no callbacks or events
available to detect pixel density changes, the only way to do so is to
periodically check the value of devicePixelRatio to see if it's
changed. Just don't do it too often, or you'll impact performance.

https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio