我在一个项目上使用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?


当前回答

也许更好的做法是不对文档的宽度进行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");
    ...
});

其他回答

这可能是由于滚动条,使用innerWidth代替width喜欢

if($(window).innerWidth() <= 751) {
   $("#body-container .main-content").remove()
                                .insertBefore($("#body-container .left-sidebar"));
} else {
   $("#body-container .main-content").remove()
                                .insertAfter($("#body-container .left-sidebar"));
}

你也可以得到视图

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

以上代码来源

如果你不需要支持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 {
    //...
}

Use

window.innerWidth

这解决了我的问题

if(window.matchMedia('(max-width: 768px)').matches)
    {
        $(".article-item").text(function(i, text) {

            if (text.length >= 150) {
                text = text.substring(0, 250);
                var lastIndex = text.lastIndexOf(" ");     
                text = text.substring(0, lastIndex) + '...'; 
            }

            $(this).text(text);

        });

    }

试试这个

getData(){
    if(window.innerWidth <= 768) {
      alert('mobile view')
      return;
    }

   //else function will work

    let body= {
      "key" : 'keyValue'
    }
    this.dataService.getData(body).subscribe(
      (data: any) => {
        this.myData = data
      }
    )
}