实时检测浏览器大小 - jQuery/JavaScript

use*_*756 20 javascript browser jquery

是否有jQuery插件或使用直接JavaScript来检测浏览器大小的方式.

我更喜欢它的结果是'实时',所以如果宽度或高度改变,结果也会改变.

Mat*_*lin 59

JavaScript的

function jsUpdateSize(){
    // Get the dimensions of the viewport
    var width = window.innerWidth ||
                document.documentElement.clientWidth ||
                document.body.clientWidth;
    var height = window.innerHeight ||
                 document.documentElement.clientHeight ||
                 document.body.clientHeight;

    document.getElementById('jsWidth').innerHTML = width;  // Display the width
    document.getElementById('jsHeight').innerHTML = height;// Display the height
};
window.onload = jsUpdateSize;       // When the page first loads
window.onresize = jsUpdateSize;     // When the browser changes size
Run Code Online (Sandbox Code Playgroud)

jQuery的

function jqUpdateSize(){
    // Get the dimensions of the viewport
    var width = $(window).width();
    var height = $(window).height();

    $('#jqWidth').html(width);      // Display the width
    $('#jqHeight').html(height);    // Display the height
};
$(document).ready(jqUpdateSize);    // When the page first loads
$(window).resize(jqUpdateSize);     // When the browser changes size
Run Code Online (Sandbox Code Playgroud)

jsfiddle演示

编辑:更新了JavaScript代码以支持IE8及更早版本.

  • 当演示在jsfiddle中运行时,它会报告演示运行的IFrame的大小.当演示在独立页面中运行时,它会报告浏览器视口的大小.我测试了两种方式.似乎工作正常. (2认同)
  • 要获得包括菜单和工具栏在内的浏览器大小,请使用`window.outerWidth`和`window.outerHeight`.但是,IE8和更早版本没有这样的选项.请参阅以下帖子:http://stackoverflow.com/questions/6291780/how-to-find-the-browser-height-including-the-toolbars-and-buttons-with-javascrip (2认同)

Ano*_*oop 6

您可以使用

function onresize (){
   var h = $(window).height(), w= $(window).width();
   $('#resultboxid').html('height= ' + h + ' width: ' w);
}
 $(window).resize(onresize ); 

 onresize ();// first time;
Run Code Online (Sandbox Code Playgroud)

HTML:

<span id=resultboxid></span>
Run Code Online (Sandbox Code Playgroud)