聆听浏览器宽度以进行响应式网页设计? [英] Listen for browser width for responsive web design?

查看:54
本文介绍了聆听浏览器宽度以进行响应式网页设计?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使我的网站移动友好.

I'm trying to make my site mobile friendly.

我想知道浏览器窗口的大小,以便在小于728px时执行某些操作,而在大于728px时执行其他操作.

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.

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

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

这怎么办?

推荐答案

正如m90所建议的,如果您唯一想做的就是修改样式,那么您应该看看

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.

普通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;
    }
}

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

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

如果您使用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:

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

这篇关于聆听浏览器宽度以进行响应式网页设计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆