jQuery和CSS媒体查询不同步 [英] jQuery and CSS media queries not in sync

查看:121
本文介绍了jQuery和CSS媒体查询不同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力了解窗口宽度是如何确定的,我想知道是否CSS和jQuery是不同的。

I've been trying to understanding the way window width is determined and I was wondering if it's different for CSS and jQuery.

如果我有CSS媒体查询:

If for example I have the CSS media query:

@media (max-width: 979px) {
  /*my css here*/
}

还有一些jQuery:

and also some jQuery:

if ($(window).width() < 979) {
  //my jQuery here
}

我会期望以下内容:
- 当浏览器调整大小时&刷新在980px,以上都将被忽略
- 当浏览器调整大小&刷新为978px,以上都会激活。

I would expect the following: - When the browser is resized & refreshed at 980px, both of the above will be ignored - When the browser is resized & refreshed at 978px, both of the above will activate.

但是我发现是
- jQuery和CSS不会直到964像素及以下。
- 有时(如果我启用了window.resize)jQuery和CSS踢在单独的宽度(几个像素分开)。

However what I'm finding is that - The jQuery and CSS don't kick in until about 964px and below. - Sometimes (if I have window.resize enabled) the jQuery and CSS kick in at seperate widths (a few pixels apart).

任何人可以脱落任何

顺便说一句,我的窗口宽度基于Firebug的布局查看器。

By the way I'm basing the window width on Firebug's layout viewer.

推荐答案

问题与滚动条宽度有关: window.innerWidth 将返回由CSS媒体查询读取的正确值。注意, $(window).innerWidth()将返回错误的值。

The problem is related to the scrollbar width: window.innerWidth will return the right value that is read by CSS media queries. Note that $(window).innerWidth() will return the wrong value.

可以使用这样的函数:

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

var value = viewport().width;

这篇关于jQuery和CSS媒体查询不同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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