javascript - CSS 和 jQuery 的宽度不同

标签 javascript jquery css

我正在设置网站的移动端,我需要为移动设备定制 CSS 和 Javascript,所以在 CSS 中我有规则使用 @media screen and (max-width: 500px) {在 Javascript 中我打算使用 if ($(window).width() < 500 .

但是,如果我将浏览器的大小调整到精确的像素,移动 CSS 就会开始被使用,并且我 console.log($(window).width());我得到 485。

这是正常行为还是我做错了什么?

更新:

使用这个,值似乎是同步的,虽然目前只在 firefox 中测试过。

var scrollBarWidth = false;


function mobileRules() {

    if (!scrollBarWidth) {
        var widthWithScrollBars = $(window).width();
        $('body').css('overflow', 'hidden');
        var widthNoScrollBars = $(window).width();
        $('body').css('overflow', 'scroll');
        scrollBarWidth = widthNoScrollBars - widthWithScrollBars;
        console.log('Width: '+widthWithScrollBars+'. Without: '+widthNoScrollBars+'. Scroll: '+scrollBarWidth);
    }

    console.log($(window).width()+scrollBarWidth+' vs '+globals.mobile_width);

    if ($(window).width()+scrollBarWidth < globals.mobile_width) {
        console.log('Running mobile rules in jQuery');
    }
}

最佳答案

在 firefox 中,媒体查询认为滚动条的宽度在屏幕宽度内。

这就是让您的屏幕宽度增加 15 像素的原因。

在基于 webkit 的浏览器中它们不会。

如果您对为什么会发生这种情况感兴趣,我将引用 this article : 的评论

A problem with Webkit browsers (that aren't following spec) is that the browser can encounter an infinite loop condition caused by media queries, which leads to a browser crash.

For example: >500px overflow-y: scroll, <500px overflow-y: hidden. Size your browser to 505px window width. Since the scroll bar subtracts 15 or so pixels from the width used by the media query, the media query flips you to < 500, but as soon as you hit <500 the scrollbar goes away, and the media query flips you to >500, and then the fun starts because now you have a scroll bar again and you're <500px and you get that style with no scroll bar... Rinse and repeat until the browser finally dies.

Now, write some javascript to calculate the media query max widths, and you have a page that will crash Chrome/Safari as soon as you load it.

My guess is that the spec was written the way it was to prevent this condition. Firefox & Opera are following spec, it's not really their fault you don't agree with spec.

关于javascript - CSS 和 jQuery 的宽度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19855290/

相关文章:

javascript - 行程优化

javascript - 将浏览器高度和宽度应用于 div

javascript - Apple store 样式固定 div 在 LEFT

html - 全视口(viewport)元素

html - div标签导致换行

CSS - 对齐页面上的图像

javascript - Api 网关无法允许 Access-Control-Allow-Origin

javascript - 是否有等效于 JavaScript 的 Array.prototype.some() 函数的 PHP

javascript - 在 for 循环内为 .setTimeout() 创建闭包

javascript - 第三个字符后的 Action 键