$(window).width()与媒体查询不一样 [英] $(window).width() not the same as media query

查看:237
本文介绍了$(window).width()与媒体查询不一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中使用Twitter Bootstrap。除了默认的引导风格我还添加了一些我自己的

I am using Twitter Bootstrap on a project. As well as the default bootstrap styles I have also added some of my own

//My styles
@media (max-width: 767px)
{
    //CSS here
}

当视口的宽度小于767像素时,我也使用jQuery来更改页面上某些元素的顺序。

I am also using jQuery to change the order of certain elements on the page when the width of the viewport is less that 767px.

$(document).load($(window).bind("resize", checkPosition));

function checkPosition()
{
    if($(window).width() < 767)
    {
        $("#body-container .main-content").remove().insertBefore($("#body-container .left-sidebar"));
    } else {
        $("#body-container .main-content").remove().insertAfter($("#body-container .left-sidebar"));
    }
}

我遇到的问题是, $(window).width()和CSS计算的宽度似乎不一样。当 $(window).width()返回767 css计算它的视口宽度为751,所以似乎有一个16px不同。

The problem I am having is that the width calculated by $(window).width() and the width calculated by the CSS doesn't seem to be the same. When $(window).width() returns 767 the css calculates it the viewport width as 751 so there seems to be a 16px different.

有没有人知道是什么原因导致这个问题,我该如何解决?人们已经建议滚动条的宽度没有考虑和使用 $(window).innerWidth()< 751 是要走的路。然而,理想情况下,我想找到一个解决方案,计算滚动条的宽度,这与我的媒体查询一致(例如,两个条件都检查值767)。因为确实不是所有的浏览器都有16px的滚动条宽度?

Does anyone know what is causing this and how I could solve the problem? People have suggested that the width of the scrollbar isn't being taken into considering and using $(window).innerWidth() < 751 is the way to go. However ideally I want to find a solution that calculates the width of the scrollbar and that is consistent with my media query (e.g where both conditions are checking against the value 767). Because surely not all browsers will have a scrollbar width of 16px?

推荐答案

如果你不需要支持IE9,使用 window.matchMedia() MDN文档)。

If you don't have to support IE9 you can just use window.matchMedia() (MDN documentation).

function checkPosition() {
    if (window.matchMedia('(max-width: 767px)').matches) {
        //...
    } else {
        //...
    }
}

window.matchMedia 与CSS媒体查询完全一致浏览器支持相当不错: http://caniuse.com/#feat=matchmedia

window.matchMedia is fully consistent with the CSS media queries and the browser support is quite good: http://caniuse.com/#feat=matchmedia

如果您必须支援更多浏览器,可以使用 Modernizr的mq方法,它支持所有了解CSS中媒体查询的浏览器。

If you have to support more browsers you can use Modernizr's mq method, it supports all browsers that understand media queries in CSS.

if (Modernizr.mq('(max-width: 767px)')) {
    //...
} else {
    //...
}

这篇关于$(window).width()与媒体查询不一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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