首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >实时检测浏览器大小- jQuery / JavaScript

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

Stack Overflow用户
提问于 2012-10-08 19:53:54
回答 6查看 62.5K关注 0票数 20

有没有jQuery插件或者直接使用JavaScript来检测浏览器大小的方法?

我更喜欢结果是“实时”的,所以如果宽度或高度改变了,结果也会改变。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2012-10-08 20:37:27

JavaScript

代码语言: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

代码语言:javascript
运行
复制
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和更早版本。

票数 60
EN

Stack Overflow用户

发布于 2012-10-08 19:56:11

您可以使用

代码语言:javascript
运行
复制
function onresize (){
   var h = $(window).height(), w= $(window).width();
   $('#resultboxid').html('height= ' + h + ' width: ' w);
}
 $(window).resize(onresize ); 

 onresize ();// first time;

html:

代码语言:javascript
运行
复制
<span id=resultboxid></span>
票数 6
EN

Stack Overflow用户

发布于 2012-10-08 19:55:21

这应该返回可见区域:

代码语言:javascript
运行
复制
document.body.offsetWidth
document.body.offsetHeight

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12781205

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档