Listen for browser width for responsive web design?

主宰稳场 提交于 2019-12-10 16:38:45

问题


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.

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

How can this be done?


回答1:


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.

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

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

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:

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



回答2:


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.



来源:https://stackoverflow.com/questions/10547876/listen-for-browser-width-for-responsive-web-design

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!