我在一个项目上使用Twitter Bootstrap。除了默认的引导样式外,我还添加了一些自己的引导样式

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

当viewport的宽度小于767px时,我还使用jQuery来改变页面上某些元素的顺序。

$(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的不同。

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


当前回答

我做什么;

<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
...

然后在任意位置调用width变量。

您需要将getWidth()放在文档主体中,以确保计算滚动条宽度,否则浏览器的滚动条宽度将从getWidth()中减去。

其他回答

也许更好的做法是不对文档的宽度进行js作用域,而是通过css @media查询进行某种更改。使用这种方法,你可以确保JQuery函数和css的变化是同时发生的。

css:

#isthin {
    display: inline-block;
    content: '';
    width: 1px;
    height: 1px;
    overflow: hidden;
}

@media only screen and (max-width: 990px) {
    #isthin {
        display: none;
    }
}

jquery:

$(window).ready(function(){
    isntMobile = $('#isthin').is(":visible");
    ...
});

$(window).resize(function(){
    isntMobile = $('#isthin').is(":visible");
    ...
});

检查媒体查询更改的CSS规则。这保证总是有效的。

http://www.fourfront.us/blog/jquery-window-width-and-media-queries

HTML:

<body>
    ...
    <div id="mobile-indicator"></div>
</body>

Javascript:

function isMobileWidth() {
    return $('#mobile-indicator').is(':visible');
}

CSS:

#mobile-indicator {
    display: none;
}

@media (max-width: 767px) {
    #mobile-indicator {
        display: block;
    }
}

Use

window.innerWidth

这解决了我的问题

我做什么;

<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
...

然后在任意位置调用width变量。

您需要将getWidth()放在文档主体中,以确保计算滚动条宽度,否则浏览器的滚动条宽度将从getWidth()中减去。

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

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

窗口。matchMedia与CSS媒体查询完全一致,浏览器支持也很好:http://caniuse.com/#feat=matchmedia

更新:

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

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