我在一个项目上使用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()中减去。

其他回答

实现光滑滑块,并根据分辨率在块中显示不同数量的幻灯片(jQuery)

   if(window.matchMedia('(max-width: 768px)').matches) {
      $('.view-id-hot_products .view-content').slick({
        infinite: true,
        slidesToShow: 3,
        slidesToScroll: 3,
        dots: true,
      });
    }

    if(window.matchMedia('(max-width: 1024px)').matches) {
      $('.view-id-hot_products .view-content').slick({
        infinite: true,
        slidesToShow: 4,
        slidesToScroll: 4,
        dots: true,
      });
    }

最好的跨浏览器解决方案是使用Modernizr.mq

链接:https://modernizr.com/docs/ mq

Modernizr。Mq允许您以编程方式检查当前浏览器窗口状态是否与媒体查询匹配。

var query = Modernizr.mq('(min-width: 900px)');
if (query) {
   // the browser window is larger than 900px
}

注意浏览器不支持媒体查询(例如旧的IE) mq总是返回false。

如果你想每1秒检查一次屏幕宽度,你可以这样做

 setInterval(function() {
        if (window.matchMedia('(max-width: 767px)').matches) {
            alert('here')
        } else {
            alert('i am ')
        }
    }, 1000);

检查媒体查询更改的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;
    }
}

是的,这是由于滚动条。正确答案来源:在这里输入链接描述

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' ] };
}