javascript 侦听响应式网页设计的浏览器宽度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10547876/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:13:19  来源:igfitidea点击:

Listen for browser width for responsive web design?

javascriptcssresponsive-design

提问by lisovaccaro

I'm trying to make my site mobile friendly.

我正在努力使我的网站对移动设备友好。

I want to know the browser window size so that I do something when it's narrower than 728px and something else when it's bigger.

我想知道浏览器窗口的大小,以便当它小于 728px 时我做一些事情,当它更大时做其他事情。

This must take into account resizing the window on the PC as well as changing from portrait to landscape mode in a phone.

这必须考虑到在 PC 上调整窗口大小以及在手机中从纵向模式更改为横向模式。

How can this be done?

如何才能做到这一点?

回答by Christofer Eliasson

As m90 suggest, if the only thing you want to do is modify the style, then you should have a look at media queries. However, if you want to do more than just modify the style, then you have to rely on JavaScript.

正如 m90 建议的那样,如果您只想修改样式,那么您应该查看media queries。但是,如果您想做的不仅仅是修改样式,那么您必须依赖 JavaScript。

Plain JavaScript

纯 JavaScript

The problem is that it isn't entirely straight forward to get the width of the window, it varies between browsers. So you would have to create a function, something like this (untested):

问题是获取窗口的宽度并不完全是直接的,它因浏览器而异。所以你必须创建一个函数,像这样(未经测试):

var width = 0;
function updateWindowSize() {
    if (document.body && document.body.offsetWidth) {
      width = document.body.offsetWidth;
    }
    if (document.compatMode=='CSS1Compat' &&
        document.documentElement &&
        document.documentElement.offsetWidth ) {
       width = document.documentElement.offsetWidth;
    }
    if (window.innerWidth) {
       width = window.innerWidth;
    }
}

Then you could listen for for the window onresize event, and call the function to get the new window size everytime the window changes.

然后您可以监听窗口 onresize 事件,并在每次窗口更改时调用该函数以获取新的窗口大小。

window.onresize = function(event) {
    updateWindowSize();
}

jQuery

jQuery

If you use jQuery, then this can be done a bit shorter, as jQuery takes care of the cross-browser-support for you behind the scenes:

如果您使用 jQuery,那么这可以做得更短一些,因为 jQuery 会在幕后为您处理跨浏览器支持:

var width;
$(window).resize(function() {
  width = $(window).width();
});

回答by LisKit

As a warning, IE8 and lower don't support media queries or CSS3. If you don't care about IE8, go for it. Respond.js, Modernizr and others can help to support IE6-8, but it's far from perfect.

作为警告,IE8 及更低版本不支持媒体查询或 CSS3。如果你不关心 IE8,那就去吧。Respond.js、Modernizr 等可以帮助支持 IE6-8,但还远远不够完美。