使用 jQuery 获取视口大小

发布于 2024-09-05 07:54:53 字数 134 浏览 5 评论 0原文

如何使用 jQuery 确定浏览器视口的大小,并在页面大小调整时重新检测它?我需要在这个空间中设置一个 IFRAME 大小(在每个边距上稍微增加一点)。

对于那些不知道的人来说,浏览器视口不是文档/页面的大小。它是滚动之前窗口的可见大小。

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).

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

无人问我粥可暖 2024-09-12 07:54:53

获取视口的宽度和高度:

var viewportWidth = $(window).width();
var viewportHeight = $(window).height();

页面的resize事件:

$(window).resize(function() {

});

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

});
找回味觉 2024-09-12 07:54:53

您可以尝试视口单位 (CSS3):

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

浏览器支持

You can try viewport units (CSS3):

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

Browser support

-小熊_ 2024-09-12 07:54:53

1.对主要问题的回应

脚本 $(window).height() 运行良好(显示视口的高度,而不是滚动高度的文档),但它需要您正确放置文档中的 doctype 标记,例如以下 doctype:

对于 HTML 5:

对于过渡 HTML4:

可能某些浏览器假定的默认文档类型是这样的,$(window).height() 采用文档的高度,而不是浏览器的高度。有了 doctype 规范,它就得到了令人满意的解决,我很确定你会避免“将滚动溢出更改为隐藏然后再返回”,我很抱歉,这是一个有点肮脏的伎俩,特别是如果你不这样做的话不要将其记录在代码中以供将来程序员使用。

2.额外提示,请注意:
此外,如果您正在编写脚本,您可以发明测试来帮助程序员使用您的库,让我发明几个:

$(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");
      } 

}) ;


编辑:关于第 2 部分,“附加提示,请注意”:
@Machiel,在昨天的评论(2014-09-04)中,完全正确:$的检查不能在Jquery的ready事件中,因为正如他指出的那样,我们假设$已经定义了。感谢您指出这一点,如果您在脚本中使用了它,请其他读者纠正这一点。我的建议是:在你的库中放置一个“install_script()”函数来初始化库(将任何对 $ 的引用放入这样的 init 函数中,包括 read() 的声明)并在这样的“install_script()”函数的开头,检查 $ 是否已定义,但使所有内容独立于 JQuery,以便您的库可以在 JQuery 尚未定义时“自我诊断”。我更喜欢这种方法,而不是强制自动创建从 CDN 带来的 JQuery。这些只是帮助其他程序员的小注释。我认为制作库的人必须对潜在程序员的错误有更丰富的反馈。例如,Google API 需要一本旁白手册来理解错误消息。这是荒谬的,需要外部文档来解决一些小错误,而不需要您去搜索手册或规范。图书馆必须是自记录的。我编写代码时甚至考虑到六个月后可能犯的错误,并且它仍然试图成为干净且不重复的代码,已经编写以防止未来开发人员犯错误。

1. Response to the main question

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:

For HTML 5:

<!DOCTYPE html>

For transitional 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. 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.

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:

$(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.

万人眼中万个我 2024-09-12 07:54:53

您可以使用 $(window).resize() 来检测视口是否已调整大小。

当存在滚动条时,jQuery 没有任何功能来一致地检测视口 [1] 的正确宽度和高度。

我找到了一个使用 Modernizr 库的解决方案,特别是使用 javascript 打开媒体查询的 mq 函数。

这是我的解决方案:

// 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();

我的答案可能不会帮助将 iframe 的大小调整为 100% 视口宽度,每侧都有边距,但我希望它能为因浏览器 JavaScript 视口宽度和高度计算的不连贯性而感到沮丧的 Web 开发人员提供安慰。

也许这对 iframe 有帮助:

$('iframe').css('width', '100%').wrap('<div style="margin:2em"></div>');

[1] 您可以使用 $(window).width() 和 $(window).height() 获取一个数字,该数字在某些浏览器中是正确的,但在其他浏览器中是不正确的。在这些浏览器中,您可以尝试使用 window.innerWidth 和 window.innerHeight 来获取正确的宽度和高度,但我建议不要使用此方法,因为它依赖于用户代理嗅探。

通常,不同的浏览器对于是否将滚动条作为窗口宽度和高度的一部分并不一致。

注意: $(window).width() 和 window.innerWidth 在使用相同浏览器的操作系统之间有所不同。
请参阅:https://github.com/eddiemachado/bones/issues/468#issuecomment -23626238

You can use $(window).resize() to detect if the viewport is resized.

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.

I found a solution that uses the Modernizr library and specifically the mq function which opens media queries for 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.

Maybe this could help with regards to the 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.

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

昇り龍 2024-09-12 07:54:53
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);
    });
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);
    });
她说她爱他 2024-09-12 07:54:53

要获取加载调整大小时视口的大小(基于 SimaWB 响应):

function getViewport() {
    var viewportWidth = $(window).width();
    var viewportHeight = $(window).height();
    $('#viewport').html('Viewport: '+viewportWidth+' x '+viewportHeight+' px');
}

getViewport();

$(window).resize(function() {
    getViewport()
});

To get size of viewport on load and on resize (based on SimaWB response):

function getViewport() {
    var viewportWidth = $(window).width();
    var viewportHeight = $(window).height();
    $('#viewport').html('Viewport: '+viewportWidth+' x '+viewportHeight+' px');
}

getViewport();

$(window).resize(function() {
    getViewport()
});
愿与i 2024-09-12 07:54:53

请注意,CSS3 视口单位(vh、vw)在 iOS 上无法正常运行。当您滚动页面时,视口大小会以某种方式重新计算,并且使用视口单位的元素的大小也会增加。所以,实际上需要一些 javascript。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文