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)
我在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)