201

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

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

当视口的宽度小于 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计算的宽度和CSS计算的宽度似乎不一样。当$(window).width()返回 767 时,css 将其视口宽度计算为 751,因此似乎有 16px 的差异。

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

4

18 回答 18

317

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

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

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

更新:

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

if (Modernizr.mq('(max-width: 767px)')) {
    //...
} else {
    //...
}
于 2014-03-28T09:12:36.990 回答
187

检查媒体查询更改的 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;
    }
}
于 2014-01-25T13:58:02.393 回答
33

这可能是由于scrollbar,使用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"));
}

你也可以得到viewport喜欢

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

以上代码源码

于 2013-10-10T09:31:17.433 回答
9

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

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' ] };
}
于 2014-02-19T14:26:51.943 回答
5

最好不要将文档的宽度限制在 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");
    ...
});
于 2014-03-25T16:57:15.163 回答
4

利用

window.innerWidth

这解决了我的问题

于 2015-01-13T21:23:50.323 回答
3

我最近遇到了同样的问题 - 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");
于 2014-03-27T09:57:25.170 回答
3

这是前面提到的依赖于通过 CSS 更改某些内容并通过 Javascript 读取它的方法的替代方法。这种方法不需要window.matchMedia或Modernizr。它也不需要额外的 HTML 元素。它通过使用 HTML 伪元素来“存储”断点信息来工作:

body:after {
  visibility: hidden;
  height: 0;
  font-size: 0;
}

@media (min-width: 20em) {
  body:after {
    content: "mobile";
  }
}

@media (min-width: 48em) {
  body:after {
    content: "tablet";
  }
}

@media (min-width: 64em) {
  body:after {
    content: "desktop";
  }
}

我用作body示例,您可以为此使用任何 HTML 元素。您可以将所需content的任何字符串或数字添加到伪元素中。不必是“移动的”等等。

现在我们可以通过以下方式从 Javascript 中读取这些信息:

var breakpoint = window.getComputedStyle(document.querySelector('body'), ':after').getPropertyValue('content').replace(/"/g,'');

if (breakpoint === 'mobile') {
    doSomething();
}

通过这种方式,我们始终可以确定断点信息是正确的,因为它直接来自 CSS,我们不必为通过 Javascript 获得正确的屏幕宽度而烦恼。

于 2016-04-18T13:40:57.583 回答
2

Javascript 提供了不止一种方法来检查视口宽度。正如您所注意到的,innerWidth 不包括工具栏宽度,并且工具栏宽度会因系统而异。还有一个outerWidth选项,它将包括工具栏的宽度。Mozilla Javascript API声明:

Window.outerWidth 获取浏览器窗口外部的宽度。它表示整个浏览器窗口的宽度,包括侧边栏(如果展开)、窗口镶边和窗口大小调整边框/句柄。

javascript 的状态是,不能依赖每个平台上每个浏览器中的 outerWidth 的特定含义。

outerWidth在较旧的移动浏览器没有得到很好的支持,尽管它在主要的桌面浏览器和大多数较新的智能手机浏览器上都受到支持。

正如 ausi 指出的那样,matchMedia这将是一个不错的选择,因为 CSS 更加标准化(matchMedia 使用 JS 来读取 CSS 检测到的视口值)。但是即使采用公认的标准,仍然存在忽略它们的延迟浏览器(在这种情况下,IE < 10,这使得 matchMedia 至少在 XP 死之前不是很有用)。

总之,如果您只是为桌面浏览器和较新的移动浏览器开发, outerWidth应该为您提供所需的内容,但有一些注意事项

于 2014-03-31T06:51:51.630 回答
1

这是处理媒体查询的一个较少涉及的技巧。跨浏览器支持有点限制,因为它不支持移动 IE。

     if (window.matchMedia('(max-width: 694px)').matches)
    {
        //do desired changes
    }

有关更多详细信息,请参阅Mozilla 文档

于 2015-04-08T17:27:40.127 回答
0

始终有效并与 CSS 媒体查询同步的解​​决方法。

将 div 添加到正文

<body>
    ...
    <div class='check-media'></div>
    ...
</body>

添加样式并通过输入特定的媒体查询来更改它们

.check-media{
    display:none;
    width:0;
}
@media screen and (max-width: 768px) {
    .check-media{
         width:768px;
    }
    ...
}

然后在 JS 中通过输入媒体查询检查您正在更改的样式

if($('.check-media').width() == 768){
    console.log('You are in (max-width: 768px)');
}else{
    console.log('You are out of (max-width: 768px)');
}

因此,通常您可以通过输入特定的媒体查询来检查正在更改的任何样式。

于 2015-04-08T16:03:26.223 回答
0
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);

        });

    }
于 2018-12-26T12:56:55.090 回答
0

最好的跨浏览器解决方案是使用 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。

于 2016-08-18T07:24:29.900 回答
0

我所做的 ;

<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>
...

然后在任何地方调用 aWidth 变量。

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

于 2019-12-29T14:50:51.960 回答
0

如果您想每 1 秒检查一次设备中的宽度屏幕,您可以这样做

 setInterval(function() {
        if (window.matchMedia('(max-width: 767px)').matches) {
            alert('here')
        } else {
            alert('i am ')
        }
    }, 1000);
于 2020-12-19T07:00:56.697 回答
0

尝试这个

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
      }
    )
}
于 2019-11-05T07:46:19.960 回答
-2

尝试这个

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

更多参考请点击这里

于 2013-10-10T09:32:07.240 回答
-2

实现光滑的滑块并根据分辨率在块中显示不同数量的幻灯片(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,
      });
    }
于 2016-12-08T09:44:34.413 回答