【问题标题】:Get the size of the screen, current web page and browser window获取屏幕、当前网页和浏览器窗口的大小
【发布时间】:2026-01-16 22:45:02
【问题描述】:

我怎样才能得到windowWidthwindowHeightpageWidthpageHeightscreenWidthscreenHeightpageXpageYscreenXscreenY所有主流浏览器?

【问题讨论】:

标签: javascript html jquery layout cross-browser


【解决方案1】:

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

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

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

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

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

【讨论】:

  • jQuery 方法 height() 似乎适用于所有元素,并返回一个数字 (46) 而不是像 css('height') ("46px") 这样的字符串。
  • 在处理移动 Safari 时,遗憾的是 jQuery 并不是这个问题的完美解决方案。请参阅第 13 行的注释github.com/jquery/jquery/blob/master/src/dimensions.js
  • @웃웃웃웃웃 您在答案中编辑了什么?根据修订,您根本没有编辑任何内容
  • @Marco Kerwitz 最糟糕的是,我输入了“javascript get window width”,而这个答案的内容在 Google 上。我的一个大减号。
  • jquery 是一个选项的 OP DID ASK。忍者编辑原始问题以排除它的人在这里有过错,而不是人们使用世俗接受的 javascript 库给出合法答案。
【解决方案2】:
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+';<br>');
document.write(center.y+';<br>');
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 плеер.--></div>');

【讨论】:

    【解决方案3】:

    这里有你需要知道的一切:Get viewport/window size

    但简而言之:

    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);
    

    Fiddle

    请停止编辑此答案。它现在已经被不同的人编辑了 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);
    

    【讨论】:

    • 为什么不g = document.body
    • @apaidnerd:IE8 等违反标准的浏览器不支持 document.body。但是,IE9 可以。
    • @MichaelMikowski 这不是真的!连IE5都支持document.body
    • @nux 我已经更正了,我已经确认支持 IE8。我知道,尽管我们最近定位的至少一个浏览器不支持 document.body,但我们不得不更改为使用 getElementsByTagName 方法。但我想我记错了浏览器。对不起!
    • 我只想非常冷静地指出,一个字母的变量名永远不会有帮助。
    【解决方案4】:

    获取可用屏幕尺寸的非 jQuery 方法。 window.screen.width/height 已经提出,但为了响应式网页设计和完整性,我认为值得一提的是这些属性:

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

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

    availWidthavailHeight - 可用的宽度和高度 屏幕(不包括操作系统任务栏等)。

    【讨论】:

      【解决方案5】:

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

      为此,请使用: window.innerWidthwindow.innerHeight 属性 (see doc at w3schools)。

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

      【讨论】:

        【解决方案6】:

        这是一个纯 JavaScript (Source) 的跨浏览器解决方案:

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

        【讨论】:

        • 这更好,因为如果您能够在加载过程中足够早地调用脚本(通常是这个想法),那么 body element 将返回 undefined 的值,因为 dom 不是尚未加载。
        • 哈!旧线程,但谢谢!我想我是那些试图在可能的情况下至少支持回到 IE8 的老“白痴”之一,以造福于数量惊人的老年家庭用户,他们在他们的机器着火之前永远不会停止使用 XP。我厌倦了提问,而不是得到答案,只被“停止支持 IE8 !!”投票否决。作为评论。再次感谢!这在我完成的纯 javascript 照片缩放中为我解决了一个问题。它在 IE8 上有点慢,但现在至少它可以工作了!!! :-)
        • @Randy 旧的 Windows XP 机器不能简单地运行新版本的 Fire-Fox 或其他什么吗?
        • @WinEunuuchs2Unix 自从我在 2016 年评论说答案解决了我的问题,为什么切换浏览器很重要?您不能告诉您的网站访问者切换浏览器。如果网站不工作,他们就会离开。 NO
        【解决方案7】:

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

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

        它添加了一个固定位置和高z-index的有效HTML,但足够小,所以你可以

        • 实际网站上使用它
        • 用它来测试移动/响应式 观看次数


        已在 Chrome 40、IE11 上测试,但也很有可能在其他/较旧的浏览器上工作... :)

          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<br>.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 );
        

        编辑: 现在样式仅适用于记录器表格元素 - 并非适用于所有表格 - 这也是一个 jQuery-free 解决方案 :)

        【讨论】:

          【解决方案8】:

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

          它只有一个目的:始终返回正确的文档大小,即使在 jQuery 和其他方法fail 的情况下也是如此。尽管有它的名字,但你不一定非得使用 jQuery——它也是用 vanilla Javascript 和 works without jQuery 编写的。

          用法:

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

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

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

          更新:现在也适用于窗口尺寸

          从 1.1.0 版开始,jQuery.documentSize 也处理窗口尺寸。

          这是必要的,因为

          • $( window ).height()buggy in iOS,到了无用的地步
          • $( window ).width()$( window ).height()unreliable on mobile 因为它们不处理移动缩放的效果。

          jQuery.documentSize 提供了$.windowWidth()$.windowHeight(),可以解决这些问题。更多内容请关注the documentation

          【讨论】:

            【解决方案9】:

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

            window.innerWidth, window.innerHeight
            

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

            【讨论】:

              【解决方案10】:

              在某些与响应式布局相关的情况下,$(document).height() 可能会返回仅显示视口高度的错误数据。 例如,当某些 div#wrapper 的高度为:100% 时,该#wrapper 可以被其中的某个块拉伸。但它的高度仍然会像视口高度。在这种情况下,您可能会使用

              $('#wrapper').get(0).scrollHeight
              

              表示包装器的实际大小。

              【讨论】:

                【解决方案11】:

                您可以使用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.availWidthscreen.availHeight

                对于pageXpageY 变量,请使用window.screenX or Y。请注意,这是来自您的左侧/顶部屏幕的最左侧/顶部。因此,如果您有两个宽度为 1920 的屏幕,那么距离右侧屏幕左侧 500 像素的窗口的 X 值为 2420 (1920+500)。但是,screen.width/height 会显示当前屏幕的宽度或高度。

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

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

                【讨论】:

                • screenX/Y 是相对于主屏幕,而不是相对于最左边/最顶部的屏幕。这就是为什么如果您当前位于主屏幕左侧的屏幕上,则该值为负数。
                【解决方案12】:

                我写了一个小的 javascript 小书签,你可以用它来显示大小。您可以轻松地将其添加到浏览器中,并且无论何时单击它,您都会在浏览器窗口的右上角看到大小。

                在这里您可以找到如何使用书签的信息 https://en.wikipedia.org/wiki/Bookmarklet

                书签

                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('<div style="'+t+'"></div>'),e=function(){return'<p style="margin:0;">width: '+i(window).width()+" height: "+i(window).height()+"</p>"},n.html(e()),i("body").prepend(n),i(window).resize(function(){n.html(e())})},(i=window.jQuery)?(i=window.jQuery,n()):(e=document.createElement("script"),e.src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",e.onload=n,document.body.appendChild(e))}()}).call(this);
                

                原码

                原代码在coffee中:

                (->
                  addWindowSize = ()->
                    style = 'background-color:azure; padding:1rem; position:fixed; right: 0; z-index:9999; font-size: 1.2rem;'
                    $windowSize = $('<div style="' + style + '"></div>')
                
                    getWindowSize = ->
                      '<p style="margin:0;">width: ' + $(window).width() + ' height: ' + $(window).height() + '</p>'
                
                    $windowSize.html getWindowSize()
                    $('body').prepend $windowSize
                    $(window).resize ->
                      $windowSize.html getWindowSize()
                      return
                
                  if !($ = window.jQuery)
                    # typeof jQuery=='undefined' works too
                    script = document.createElement('script')
                    script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'
                    script.onload = addWindowSize
                    document.body.appendChild script
                  else
                    $ = window.jQuery
                    addWindowSize()
                )()
                

                基本上,代码会在您调整窗口大小时更新一个小 div。

                【讨论】:

                  【解决方案13】:

                  我开发了一个库,用于了解台式机和移动浏览器的真实视口大小,因为视口大小在设备之间不一致,并且不能依赖该帖子的所有答案(根据我对此所做的所有研究):@987654321 @

                  【讨论】:

                    【解决方案14】:

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

                    第一步:点击鼠标右键,点击“Inspect”,然后点击“console”

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

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

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

                    【讨论】:

                      【解决方案15】:

                      这是我的解决方案!

                      // 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 = \n`, console_color, JSON.stringify(i_obj, null, 4));
                          let o_obj = screen_viewport_outer();
                          console.log(`%c screen_viewport_outer = \n`, console_color, JSON.stringify(o_obj, null, 4));
                      };
                      
                      // IIFE
                      (() => {
                          test();
                      })();

                      【讨论】:

                      【解决方案16】:

                      这是我在 React JS 项目中获得屏幕宽度的方法:

                      如果宽度等于 1680 则返回 570 否则返回 200

                      var screenWidth = window.screen.availWidth;
                      
                      <Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a  </Label>
                      

                      Screen.availWidth

                      【讨论】:

                        【解决方案17】:

                        与屏幕尺寸相关的完整指南

                        JavaScript

                        身高:

                        document.body.clientHeight  // Inner height of the HTML document body, including padding 
                                                    // but not the horizontal scrollbar height, border, or margin
                        
                        screen.height               // Device screen height (i.e. all physically visible stuff)
                        screen.availHeight          // Device screen height minus the operating system taskbar (if present)
                        window.innerHeight          // The current document's viewport height, minus taskbars, etc.
                        window.outerHeight          // Height the current window visibly takes up on screen 
                                                    // (including taskbars, menus, etc.)
                        

                        注意:当窗口最大化时,这将等于 screen.availHeight

                        对于宽度:

                        document.body.clientWidth   // Full width of the HTML page as coded, minus the vertical scroll bar
                        screen.width                // Device screen width (i.e. all physically visible stuff)
                        screen.availWidth           // Device screen width, minus the operating system taskbar (if present)
                        window.innerWidth           // The browser viewport width (including vertical scroll bar, includes padding but not border or margin)
                        window.outerWidth           // The outer window width (including vertical scroll bar,
                                                    // toolbars, etc., includes padding and border but not margin)
                        

                        Jquery

                        身高:

                        $(document).height()    // Full height of the HTML page, including content you have to 
                                                // scroll to see
                        
                        $(window).height()      // The current document's viewport height, minus taskbars, etc.
                        $(window).innerHeight() // The current document's viewport height, minus taskbars, etc.
                        $(window).outerHeight() // The current document's viewport height, minus taskbars, etc.                         
                        

                        对于宽度:

                        $(document).width()     // The browser viewport width, minus the vertical scroll bar
                        $(window).width()       // The browser viewport width (minus the vertical scroll bar)
                        $(window).innerWidth()  // The browser viewport width (minus the vertical scroll bar)
                        $(window).outerWidth()  // The browser viewport width (minus the vertical scroll bar)
                        

                        参考:https://help.optimizely.com/Build_Campaigns_and_Experiments/Use_screen_measurements_to_design_for_responsive_breakpoints

                        【讨论】:

                          【解决方案18】:

                          通过在ES2020 中引入globalThis,您可以使用类似的属性。

                          对于屏幕尺寸:

                          globalThis.screen.availWidth 
                          globalThis.screen.availHeight
                          

                          对于窗口大小

                          globalThis.outerWidth
                          globalThis.outerHeight
                          

                          对于偏移:

                          globalThis.pageXOffset
                          globalThis.pageYOffset
                          

                          ...等等。

                          alert("Screen Width: "+ globalThis.screen.availWidth +"\nScreen Height: "+ globalThis.screen.availHeight)

                          【讨论】:

                            【解决方案19】:

                            2020 年全年

                            我很惊讶这个问题大约有 10 年的时间,而且到目前为止似乎还没有人给出完整的答案(有 10 个值)。所以我仔细分析了OP问题(特别是图片)并发表了一些评论

                            • 坐标系中心(0,0)在视口中(浏览器窗口没有条和主边框)左上角和轴指向右下角(OP图片上标记的)所以pageX, pageY, screenX, screenY的值必须为负数(如果页面很小或未滚动,则为零)
                            • 对于screenHeight/Width OP 想要计算屏幕高度/宽度,包括系统菜单栏(例如在 MacOs 中) - 这就是我们不使用 .availWidth/Height 的原因(不计算在内)
                            • 对于windowWidth/Height OP 不想计算滚动条的大小,所以我们使用.clientWidth/Height
                            • screenY - 在下面的解决方案中,我们添加到浏览器左上角的位置 (window.screenY) 其菜单/tabls/url 栏的高度。但是,如果下载底部栏出现在浏览器中和/或如果开发人员控制台在页面底部打开,则很难计算该值 - 在这种情况下,该值将在下面的解决方案中增加该栏/控制台高度的大小。可能无法读取条形图/控制台高度的值来进行校正(没有一些技巧,例如要求用户在测量之前关闭该条形图/控制台......)
                            • pageWidth - 如果 pageWidth 小于 windowWidth,我们需要手动计算 &lt;body&gt; 子元素的大小以获得该值(我们在下面的解决方案中在 contentWidth 中进行示例计算 - 但通常这可能很难案例)
                            • 为简单起见,我假设&lt;body&gt; margin=0 - 如果不是,那么您在计算pageWidth/HeightpageX/Y 时应该考虑这个值

                            function sizes() {
                              let contentWidth = [...document.body.children].reduce( 
                                (a, el) => Math.max(a, el.getBoundingClientRect().right), 0) 
                                - document.body.getBoundingClientRect().x;
                            
                              return {
                                windowWidth:  document.documentElement.clientWidth,
                                windowHeight: document.documentElement.clientHeight,
                                pageWidth:    Math.min(document.body.scrollWidth, contentWidth),
                                pageHeight:   document.body.scrollHeight,
                                screenWidth:  window.screen.width,
                                screenHeight: window.screen.height,
                                pageX:        document.body.getBoundingClientRect().x,
                                pageY:        document.body.getBoundingClientRect().y,
                                screenX:     -window.screenX,
                                screenY:     -window.screenY - (window.outerHeight-window.innerHeight),
                              }
                            }
                            
                            
                            
                            // TEST
                            
                            function show() {
                              console.log(sizes());
                            }
                            body { margin: 0 }
                            .box { width: 3000px; height: 4000px; background: red; }
                            <div class="box">
                              CAUTION: * snippet gives wrong values for screenX-Y, 
                              but if you copy this code to your page directly the values will be right<br>
                              <button onclick="show()" style="">CALC</button>
                            </div>

                            我在 MacOs High Sierra 上的 Chrome 83.0、Safari 13.1、Firefox 77.0 和 Edge 83.0 上对其进行了测试

                            【讨论】:

                            【解决方案20】:

                            图形答案: (…………)

                            【讨论】:

                              最近更新 更多