代码之家  ›  专栏  ›  技术社区  ›  turtledove

获取屏幕、当前网页和浏览器窗口的大小

  •  1786
  • turtledove  · 技术社区  · 16 年前

    如何获得 windowwidth , windowheight , pagewidth , pageheight , screenwidth , screenheight , pagex , pagey , screenx , screeny which will work in all major browsers?

    , screenWidth , screenHeight , pageX , pageY , screenX , screenY 在所有主要的浏览器中,哪一个都有效?

    16 回复  |  直到 7 年前
        1
  •  1254
  •   Ankit Jaiswal    7 年前

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

    $(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 对象的方式如下:

    screen.height;
    screen.width;
    
        2
  •  881
  •   wjandrea sebs    7 年前

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

    但简而言之:

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

    Fiddle

        3
  •  425
  •   Michael asterite    11 年前

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

    var width = window.innerWidth
    || document.documentElement.clientWidth
    || document.body.clientWidth;
    
    var height = window.innerHeight
    || document.documentElement.clientHeight
    || document.body.clientHeight;
    
        4
  •  84
  •   Daniel W.    12 年前

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

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

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

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

        5
  •  60
  •   Aabha Pandey    11 年前

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

    window.innerWidth, window.innerHeight
    

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

        6
  •  18
  •   solanki...    10 年前

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

    步骤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)
    
        7
  •  17
  •   serfer2    12 年前

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

    为此,请使用: window.innerWidth window.innerHeight 性能( see doc at w3schools )

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

        8
  •  17
  •   Jonatas Walker    10 年前
    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>');
    
        9
  •  10
  •   Community Mohan Dere    9 年前

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

    它只有一个目的:总是返回正确的文档大小,即使在jquery和其他方法的场景中也是如此。 fail . 尽管它的名字,但您不必使用jquery“它是用普通的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还处理窗口尺寸。

    这是必要的,因为

    jquery.documentsize提供 $.windowWidth() $.windowHeight() 解决了这些问题。更多信息,请查看 the documentation .

        10
  •  8
  •   Andi Giga    10 年前

    我写了一个小的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);
    

    原始代码

    原始代码在咖啡中:

    (->
      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前面加上一个DIV,当您调整窗口大小时,它会更新。

        11
  •  5
  •   Akim Kelar    10 年前

    在某些情况下,与响应式布局有关 $(document).height() 只能返回显示视图端口高度的错误数据。 例如,当某个DIV包装器的高度为100%时,该包装器可以通过其内部的某个块拉伸。但它的高度仍然和视区高度一样。在这种情况下,你可能会使用

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

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

        12
  •  4
  •   pyrsmk    10 年前

    我开发了一个库,用于了解桌面和移动浏览器的实际视区大小,因为视区大小在设备之间是不一致的,不能依赖于文章的所有答案(根据我对此所做的所有研究): https://github.com/pyrsmk/W

        13
  •  3
  •   jave.web    10 年前

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

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

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

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


    测试对象:Chrome40、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 );
    

    编辑: 现在样式只应用于logger table元素,而不是所有表,这也是 免费查询 解决方案:

        14
  •  2
  •   Endless TheZver    10 年前

    你可以使用 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.availHeight 分别。

    对于 pageX pageY 变量,使用 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 为了你 帕克斯 帕吉 价值观。

        15
  •  0
  •   user8202629    9 年前

    这是我的解决方案!

    // 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
  •  -1
  •   NVRM    8 年前

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

    语法有点清楚!

    n = "<i>px</i><br>"  /* 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像素比率返回 物理像素的分辨率为 当前显示设备。该值也可以解释为 像素大小比率:一个CSS像素的大小与一个CSS像素的大小之比 物理像素。简单来说,这会告诉浏览器 屏幕的实际像素应用于绘制单个CSS像素。

    这在处理在 标准显示与Hidpi或视网膜显示相比,后者使用更多 屏幕像素绘制相同的对象,从而产生更清晰的图像。

    当此值更改时,无法通知(可以 例如,如果用户将窗口拖动到带有 不同的像素密度)。因为没有回调或事件 可用于检测像素密度变化,唯一的方法是 定期检查device像素比的值,看它是否 改变。只是不要经常这样做,否则会影响性能。

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