CSS媒体查询和JavaScript窗口宽度不匹配 [英] CSS media queries and JavaScript window width do not match

查看:138
本文介绍了CSS媒体查询和JavaScript窗口宽度不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For a responsive template, I have a media query in my CSS:

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

而且,我在调整大小时创建了一个jQuery函数来记录width:

And, I made a jQuery function on resize to log width:

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

与CSS检测和JS结果存在差异,我有这个元:

And there a difference with CSS detection and JS result, I have this meta:

<meta content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, width=device-width" name="viewport"/> 

我想这是由滚动条(15像素)引起的。我怎么能这样做更好吗?

I suppose it's due to the scrollbar (15 px). How can I do this better?

推荐答案

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

You're correct about the scroll bar, it's because the CSS is using the device width, but the JS is using the document width.

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

What you need to do is measure the viewport width in your JS code instead of using the jQuery width function.

这个鳕鱼e来自 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' ] };
}

这篇关于CSS媒体查询和JavaScript窗口宽度不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆