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

时间:2012-10-08 11:53:54

标签: javascript jquery browser

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

我更喜欢结果是“实时”,所以如果宽度或高度发生变化,结果也会发生变化。

6 个答案:

答案 0 :(得分: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

<强>的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

jsfiddle demo

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

答案 1 :(得分:6)

你可以使用

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

 onresize ();// first time;

HTML:

<span id=resultboxid></span>

答案 2 :(得分:2)

这应该返回可见区域:

document.body.offsetWidth
document.body.offsetHeight

我猜这总是等于浏览器大小?

答案 3 :(得分:2)

在任何你想要的地方使用宽度和高度变量...当浏览器大小改变时,它也会改变变量值..

$(window).resize(function() {
    width = $(this).width());
    height = $(this).height());
});

答案 4 :(得分:0)

您的意思是window.innerHeight; window.innerWidth $(window).height(); $(window).width()

答案 5 :(得分:0)

您可以尝试在调整大小时添加事件侦听器,如

window.addEventListener('resize',CheckBrowserSize,false);
function CheckBrowserSize() 
{
    var ResX= document.body.offsetHeight;
    var ResY= document.body.offsetWidth;
}