使用 jQuery 获取视口的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3044573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using jQuery To Get Size of Viewport
提问by Volomike
How do I use jQuery to determine the size of the browser viewport, and to redetect this if the page is resized? I need to make an IFRAME size into this space (coming in a little on each margin).
如何使用 jQuery 确定浏览器视口的大小,并在页面调整大小时重新检测?我需要在这个空间中制作一个 IFRAME 大小(每个边距都有一点)。
For those who don't know, the browser viewport is not the size of the document/page. It is the visible size of your window before the scroll.
对于那些不知道的人,浏览器视口不是文档/页面的大小。它是滚动前窗口的可见大小。
回答by SimaWB
To get the width and height of the viewport:
获取视口的宽度和高度:
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
resize event of the page:
页面调整大小事件:
$(window).resize(function() {
});
回答by Vitalii Fedorenko
回答by David L
1. Response to the main question
1. 对主要问题的回应
The script $(window).height()
does work well (showing the viewport's height and not the document with scrolling height), BUT it needs that you put correctly the doctype tag in your document, for example these doctypes:
该脚本运行$(window).height()
良好(显示视口的高度而不是具有滚动高度的文档),但它需要您在文档中正确放置 doctype 标签,例如这些 doctypes:
For HTML 5:
对于 HTML 5:
<!DOCTYPE html>
<!DOCTYPE html>
For transitional HTML4:
对于过渡 HTML4:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Probably the default doctype assumed by some browsers is such, that $(window).height()
takes the document's height and not the browser's height. With the doctype specification, it's satisfactorily solved, and I'm pretty sure you peps will avoid the "changing scroll-overflow to hidden and then back", which is, I'm sorry, a bit dirty trick, specially if you don't document it on the code for future programmer's usage.
可能某些浏览器假定的默认文档类型是这样的,即$(window).height()
采用文档的高度而不是浏览器的高度。使用文档类型规范,它得到了令人满意的解决,我很确定你会避免“将滚动溢出更改为隐藏然后返回”,对不起,这是一个有点肮脏的技巧,特别是如果你不这样做' t 将其记录在代码中以供将来程序员使用。
2. An ADDITIONAL tip, note aside:Moreover, if you are doing a script, you can invent tests to help programmers in using your libraries, let me invent a couple:
2. 一个额外的技巧,请注意:此外,如果你正在做一个脚本,你可以发明测试来帮助程序员使用你的库,让我发明几个:
$(document).ready(function() {
$(document).ready(function() {
if(typeof $=='undefined') {
alert("PROGRAMMER'S Error: you haven't called JQuery library");
} else if (typeof $.ui=='undefined') {
alert("PROGRAMMER'S Error: you haven't installed the UI Jquery library");
}
if(document.doctype==null || screen.height < parseInt($(window).height()) ) {
alert("ERROR, check your doctype, the calculated heights are not what you might expect");
}
});
});
EDIT: about the part 2, "An ADDITIONAL tip, note aside": @Machiel, in yesterday's comment (2014-09-04), was UTTERLY right: the check of the $ can not be inside the ready event of Jquery, because we are, as he pointed out, assuming $ is already defined. THANKS FOR POINTING THAT OUT, and do please the rest of you readers correct this, if you used it in your scripts. My suggestion is: in your libraries put an "install_script()" function which initializes the library (put any reference to $ inside such init function, including the declaration of ready()) and AT THE BEGINNING of such "install_script()" function, check if the $ is defined, but make everything independent of JQuery, so your library can "diagnose itself" when JQuery is not yet defined. I prefer this method rather than forcing the automatic creation of a JQuery bringing it from a CDN. Those are tiny notes aside for helping out other programmers. I think that people who make libraries must be richer in the feedback to potential programmer's mistakes. For example, Google Apis need an aside manual to understand the error messages. That's absurd, to need external documentation for some tiny mistakes that don't need you to go and search a manual or a specification. The library must be SELF-DOCUMENTED. I write code even taking care of the mistakes I might commit even six months from now, and it still tries to be a clean and not-repetitive code, already-written-to-prevent-future-developer-mistakes.
编辑:关于第 2 部分,“附加提示,请注意”:@Machiel,在昨天的评论 (2014-09-04) 中,完全正确:$ 的检查不能在 Jquery 的就绪事件中,因为正如他所指出的,我们假设 $ 已经定义。感谢您指出这一点,如果您在脚本中使用了它,请其他读者纠正这一点。我的建议是:在你的库中放置一个“install_script()”函数来初始化库(在这样的 init 函数中放置对 $ 的任何引用,包括 ready() 的声明)和这样的“install_script()”函数的开始,检查 $ 是否已定义,但使所有内容独立于 JQuery,以便您的库可以在 JQuery 尚未定义时“自我诊断”。我更喜欢这种方法,而不是强制自动创建一个 JQuery,将它从 CDN 中引入。这些是帮助其他程序员的小笔记。我认为制作库的人对潜在的程序员错误的反馈必须更丰富。例如,Google Apis 需要一本手册来理解错误信息。这是荒谬的,需要外部文档来解决一些不需要您去搜索手册或规范的小错误。图书馆必须是自我记录的。我编写代码时甚至会考虑我可能在六个月后犯的错误,并且它仍然试图成为干净且不重复的代码,已经编写以防止未来开发人员的错误。我认为制作库的人对潜在的程序员错误的反馈必须更丰富。例如,Google Apis 需要一本手册来理解错误信息。这是荒谬的,需要外部文档来解决一些不需要您去搜索手册或规范的小错误。图书馆必须是自我记录的。我编写代码时甚至会考虑我可能在六个月后犯的错误,并且它仍然试图成为干净且不重复的代码,已经编写以防止未来开发人员的错误。我认为制作库的人对潜在程序员错误的反馈必须更丰富。例如,Google Apis 需要一本手册来理解错误信息。这是荒谬的,需要外部文档来解决一些不需要您去搜索手册或规范的小错误。图书馆必须是自我记录的。我编写代码时甚至会考虑我可能在六个月后犯的错误,并且它仍然试图成为干净且不重复的代码,已经编写以防止未来开发人员的错误。不需要你去搜索手册或规范。图书馆必须是自我记录的。我编写代码时甚至会考虑从现在起六个月后可能犯的错误,并且它仍然试图成为干净且不重复的代码,已经编写以防止未来开发人员的错误。不需要你去搜索手册或规范。图书馆必须是自我记录的。我编写代码时甚至会考虑我可能在六个月后犯的错误,并且它仍然试图成为干净且不重复的代码,已经编写以防止未来开发人员的错误。
回答by forsvunnet
You can use $(window).resize() to detect if the viewport is resized.
您可以使用 $(window).resize() 来检测视口是否已调整大小。
jQuery does not have any function to consistently detect the correctly width and height of the viewport[1] when there is a scroll bar present.
当存在滚动条时,jQuery 没有任何功能可以一致地检测视口 [1] 的正确宽度和高度。
I found a solution that uses the Modernizr library and specifically the mq function which opens media queries for javascript.
我找到了一个使用 Modernizr 库的解决方案,特别是 mq 函数,它为 javascript 打开媒体查询。
Here is my solution:
这是我的解决方案:
// A function for detecting the viewport minimum width.
// You could use a similar function for minimum height if you wish.
var min_width;
if (Modernizr.mq('(min-width: 0px)')) {
// Browsers that support media queries
min_width = function (width) {
return Modernizr.mq('(min-width: ' + width + ')');
};
}
else {
// Fallback for browsers that does not support media queries
min_width = function (width) {
return $(window).width() >= width;
};
}
var resize = function() {
if (min_width('768px')) {
// Do some magic
}
};
$(window).resize(resize);
resize();
My answer will probably not help resizing a iframe to 100% viewport width with a margin on each side, but I hope it will provide solace for webdevelopers frustrated with browser incoherence of javascript viewport width and height calculation.
我的回答可能无助于将 iframe 的大小调整为 100% 视口宽度,每边都有一个边距,但我希望它能够为因浏览器不连贯的 JavaScript 视口宽度和高度计算而感到沮丧的 web 开发人员提供安慰。
Maybe this could help with regards to the iframe:
也许这对 iframe 有帮助:
$('iframe').css('width', '100%').wrap('<div style="margin:2em"></div>');
[1] You can use $(window).width() and $(window).height() to get a number which will be correct in some browsers, but incorrect in others. In those browsers you can try to use window.innerWidth and window.innerHeight to get the correct width and height, but i would advice against this method because it would rely on user agent sniffing.
[1] 您可以使用 $(window).width() 和 $(window).height() 来获取在某些浏览器中正确但在其他浏览器中不正确的数字。在这些浏览器中,您可以尝试使用 window.innerWidth 和 window.innerHeight 来获得正确的宽度和高度,但我建议不要使用这种方法,因为它依赖于用户代理嗅探。
Usually the different browsers are inconsistent about whether or not they include the scrollbar as part of the window width and height.
通常,不同的浏览器对于是否将滚动条作为窗口宽度和高度的一部分是不一致的。
Note: Both $(window).width() and window.innerWidth vary between operating systems using the same browser. See: https://github.com/eddiemachado/bones/issues/468#issuecomment-23626238
注意: $(window).width() 和 window.innerWidth 在使用相同浏览器的操作系统之间有所不同。参见:https: //github.com/eddiemachado/bones/issues/468#issuecomment-23626238
回答by AnuRaj
function showViewPortSize(display) {
if (display) {
var height = window.innerHeight;
var width = window.innerWidth;
jQuery('body')
.prepend('<div id="viewportsize" style="z-index:9999;position:fixed;bottom:0px;left:0px;color:#fff;background:#000;padding:10px">Height: ' + height + '<br>Width: ' + width + '</div>');
jQuery(window)
.resize(function() {
height = window.innerHeight;
width = window.innerWidth;
jQuery('#viewportsize')
.html('Height: ' + height + '<br>Width: ' + width);
});
}
}
$(document)
.ready(function() {
showViewPortSize(true);
});
回答by SandroMarques
To get size of viewport on loadand on resize(based on SimaWB response):
在加载和调整大小时获取视口的大小(基于 SimaWB 响应):
function getViewport() {
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
$('#viewport').html('Viewport: '+viewportWidth+' x '+viewportHeight+' px');
}
getViewport();
$(window).resize(function() {
getViewport()
});
回答by D.A.H
Please note that CSS3 viewport units (vh,vw) wouldn't play well on iOS When you scroll the page, viewport size is somehow recalculated and your size of element which uses viewport units also increases. So, actually some javascript is required.
请注意,CSS3 视口单位 (vh,vw) 在 iOS 上效果不佳当您滚动页面时,视口大小会以某种方式重新计算,并且使用视口单位的元素大小也会增加。所以,实际上需要一些javascript。