CSS媒体查询和JavaScript窗口宽度不匹配

ben*_*oît 50 javascript jquery media-queries

对于响应式模板,我在CSS中有一个媒体查询:

@media screen and (max-width: 960px) {
 body{
 /*  something */
 background:red;
 }
}
Run Code Online (Sandbox Code Playgroud)

并且,我在调整大小到日志宽度时创建了一个jQuery函数:

$(window).resize(function() {
 console.log($(window).width());
 console.log($(document).width()); /* same result */
 /* something for my js navigation */
}
Run Code Online (Sandbox Code Playgroud)

与CSS检测和JS结果有区别,我有这个元:

<meta content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, width=device-width" name="viewport"/> 
Run Code Online (Sandbox Code Playgroud)

我想这是由于滚动条(15像素).我怎么能做得更好?

小智 74

你对滚动条的看法是正确的,因为CSS使用的是设备宽度,但JS使用的是文档宽度.

您需要做的是在JS代码中测量视口宽度,而不是使用jQuery宽度函数.

此代码来自http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/

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' ] };
}
Run Code Online (Sandbox Code Playgroud)

  • 如果窗口有滚动条并且您的媒体查询正在检查max-width,这似乎不起作用,至少在Chrome中是这样.检查一个你知道的元素上的css是由特定的媒体查询设置的,但似乎可以正常工作. (3认同)

Lar*_*arS 7

我在http://www.w3schools.com/js/js_window.asp上找到了以下代码:

var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
Run Code Online (Sandbox Code Playgroud)

实际上它的工作方式与@Michael Bird的答案相同,但它更容易阅读.

编辑:我正在寻找一种方法来提供与用于css媒体查询完全相同的宽度.但是建议的那个在使用滚动条的Safari上并不完美,抱歉.我最终在一个中心函数中使用了modernizr.js,在其余代码中我只检查显示类型是移动设备,平板电脑还是桌面设备.由于我对宽度不感兴趣,这对我来说很好:

getDisplayType = function () {
  if (Modernizr.mq('(min-width: 768px)')){
    return 'desktop';
  }
  else if (Modernizr.mq('(min-width: 480px)')){
    return 'tablet'
  }
  return 'mobile';
};
Run Code Online (Sandbox Code Playgroud)

  • @ausi:请你比"不信任w3schools"更善良,更精致吗?到目前为止我看不到问题.另请参阅[document.documentElement的任何跨浏览器问题](http://stackoverflow.com/questions/11391827/any-cross-browser-issues-with-document-documentelement) (3认同)

Ros*_*oss 6

window.innerWidth 是你所需要的。

if (window.innerWidth < 768) 适用于 CSS 中的 768 断点