[英]Get constant browser height and width
I was wondering how I could constantly get the current browser's height and width. 我想知道如何不断获取当前浏览器的高度和宽度。 Right now, I am using jQuery and have something like this:
现在,我正在使用jQuery并具有以下内容:
var height = window.innerHeight;
var width = window.innerWidth;
This does initially work as it gets the screen when the page is loaded up. 最初在页面加载时它会获得屏幕,因此它确实起作用。 However, when the user changes the screen width/height manually, I can't seem to get the current dimensions and the page starts faulting with errors.
但是,当用户手动更改屏幕宽度/高度时,我似乎无法获取当前尺寸,并且页面开始出现错误。 How should I be checking the dimensions at all times?
我应该如何一直检查尺寸? I've tried googling the answer but I can't seem to find anything applicable, though I'm sure many others have had the same issue (I don't think I'm searching up the right keywords!).
我已经尝试过搜索答案,但似乎无法找到任何适用的方法,尽管我确定许多其他人也遇到了同样的问题(我不认为自己正在寻找正确的关键字!)。 Please let me know what I can do!!
请让我知道我能做什么! Thanks!
谢谢!
Use a window.onresize
function as well as a window.onload
handler to update the width and height variables. 使用
window.onresize
函数以及window.onload
处理函数来更新width和height变量。
( Resizeable Demo ) ( 可调整大小的演示 )
var width,height; window.onresize = window.onload = function() { width = this.innerWidth; height = this.innerHeight; document.body.innerHTML = width + 'x' + height; // For demo purposes }
Using jQuery objects it would look like this. 使用jQuery对象,它看起来像这样。
( Resizeable Demo ) ( 可调整大小的演示 )
var width,height; $(window).on('load resize', function() { width = this.innerWidth; // `this` points to the DOM object, not the jQuery object height = this.innerHeight; document.body.innerHTML = width + 'x' + height; // For demo purposes });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this 尝试这个
var width = window.outerWidth;
var height = window.outerHeight;
To resize the current window, use 要调整当前窗口的大小,请使用
window.resizeTo(width, height);
You can trigger the resize function using: 您可以使用以下方法触发调整大小功能:
$( window ).resize(function() {
//....
});
Hope it helps you 希望对您有帮助
You can use this to detect a change in screen size: 您可以使用它来检测屏幕尺寸的变化:
$(window).resize(function() {
height = window.innerHeight;
width = window.innerWidth;
//other code you wish to run on screen size change;
});
This assumes that height
and width
were declared in a scope that the function has access to. 假定
height
和width
是在函数可以访问的范围内声明的。 Otherwise make sure to place var
before each variable. 否则,请确保将
var
放在每个变量之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.