我很困惑,仍然不知道如何用恰当的语言来解释这一点。到目前为止,我已经使用断点设置了我的媒体查询。使用的断点变量看起来像例如:
$menustatictofixed: min-width 900px;
$breakpoint-to-ems 设置为 true。我根据以下 jQuery 片段的像素值布置了包含所有断点变量的页面:
$('body').append('<div style="position: fixed; bottom: 0; right: 0; display: inline-block; font-weight: bold; padding: 5px 7px; border-radius: 5px 0 0 0; background: green; color: white; z-index: 9999;">Viewport width <span id="width"></span> px</div>');
var viewportWidth = $(window).width()
$('#width').text(viewportWidth);
$(window).resize(function() {
var viewportWidth = $(window).width();
$('#width').text(viewportWidth);
});
一切看起来都干净整洁。但是在过去的一两天里,我在为模式设置最后一个断点并让事情表现可预测时遇到了问题。不知何故,一开始看起来干净整洁的事情,我现在逻辑上高度怀疑,实际上是不正确的,不知何故一团糟。因为如果你看看下面的 screenshot不知何故,窗口的宽度(在 Chrome 中)不同于使用 window.width 的 jQuery 片段的宽度。如果我将 window.width 替换为 window.innerWidth 以最终排除滚动条,也没有区别。获得正确结果的唯一方法是在等式中添加 15 个像素:
var viewportWidth = $(window).width() + 15;
整个等式中唯一的问题是 window.width 是函数的错误选择,最好使用例如document.documentElement.clientWidth 或其他东西或...? 15 个像素代表什么,它以有点古怪的方式解决了上述问题?最好的问候拉尔夫
最佳答案
这对我有用: CSS media queries and JavaScript window width do not match .
不是使用包含滚动条的 $(window).width();
而是像这样获取内部宽度:
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' ] };
}
var vpWidth = viewport().width; // This should match your media query
关于jquery - 为什么 window.width 小于媒体查询中设置的视口(viewport)宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18546067/