使用jQuery获取视口大小

本文翻译自:Using jQuery To Get Size of Viewport

How do I use jQuery to determine the size of the browser viewport, and to redetect this if the page is resized? 如何使用jQuery来确定浏览器视口的大小,并在页面调整大小时重新检测? I need to make an IFRAME size into this space (coming in a little on each margin). 我需要在这个空间中建立一个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. 它是滚动前窗口的可见大小。


#1楼

参考:https://stackoom.com/question/Cm21/使用jQuery获取视口大小


#2楼

You can try viewport units (CSS3): 您可以尝试视口单元 (CSS3):

div { 
  height: 95vh; 
  width: 95vw; 
}

Browser support 浏览器支持


#3楼

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库的解决方案,特别是用于打开javascript媒体查询的mq函数。

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%视口宽度,每边都有一个边距,但我希望它能为web开发者提供安慰,因为javascript视口宽度和高度计算的浏览器不连贯感到沮丧。

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. [1]您可以使用$(window).width()和$(window).height()来获取在某些浏览器中正确的数字,但在其他浏览器中则不正确。 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. 在这些浏览器中,您可以尝试使用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. 注意:$(window).width()和window.innerWidth在使用相同浏览器的操作系统之间有所不同。 See: https://github.com/eddiemachado/bones/issues/468#issuecomment-23626238 请参阅: https//github.com/eddiemachado/bones/issues/468#issuecomment-23626238


#4楼

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. 请注意,CSS3视口单元(vh,vw)在iOS上无法正常播放当您滚动页面时,视口大小会以某种方式重新计算,并且使用视口单元的元素大小也会增加。 So, actually some javascript is required. 所以,实际上需要一些JavaScript。


#5楼

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>

For transitional HTML4: 对于过渡HTML4:

<!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. 某些浏览器假定的默认doctype可能是这样的, $(window).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. 有了doctype规范,它已经圆满解决了,我很确定你会避免“将滚动溢出更改为隐藏然后返回”,也就是说,对不起,有点肮脏的伎俩,特别是如果你不这样做将其记录在代码上以供将来程序员使用。

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. 编辑:关于第2部分,“附加提示,请注意”:@Machiel,在昨天的评论(2014-09-04)中,是完全正确的:$的检查不能在Jquery的准备事件中,因为正如他所指出的,我们正在假设已定义$。 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. 我的建议是:在你的库中放入一个“install_script()”函数来初始化库(在这样的init函数中放入任何对$的引用,包括ready()的声明)和这样的“install_script()”函数的开始,检查是否定义了$,但是使所有内容都独立于JQuery,因此当JQuery尚未定义时,您的库可以“自我诊断”。 I prefer this method rather than forcing the automatic creation of a JQuery bringing it from a CDN. 我更喜欢这种方法而不是强制自动创建一个从CDN引入它的JQuery。 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. 例如,Google Apis需要另外的手册才能理解错误消息。 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. 我编写代码甚至可以处理我可能在六个月后犯下的错误,它仍然试图成为一个干净且不重复的代码,已经编写为防止未来的开发人员错误。


#6楼

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() {

});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值