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


当前回答

试试这个

if (document.documentElement.clientWidth < 767) {
   // scripts
}

更多参考请点击这里

其他回答

试试这个

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
      }
    )
}

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

我最近也遇到了同样的问题——同样是Bootstrap 3。

无论是$.width()或$. innerwidth()将为您工作。

我想出的最好的解决方案是专门为BS3量身定制的 是检查.container元素的宽度。

你可能知道.container元素是如何工作的, 它是唯一的元素,将给你当前宽度设置由BS css规则。

它是这样的

bsContainerWidth = $("body").find('.container').width()
if (bsContainerWidth <= 768)
    console.log("mobile");
else if (bsContainerWidth <= 950)
    console.log("small");
else if (bsContainerWidth <= 1170)
    console.log("medium");
else
    console.log("large");

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

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

试试这个

if (document.documentElement.clientWidth < 767) {
   // scripts
}

更多参考请点击这里