我尝试使用以下代码来测试Modernizr.mq,我想加载yep
的js代码。
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>S123</title>
<link rel="stylesheet" href="css/s.css" />
<script src="js/modernizr.com.js"></script>
</head>
<body>
<script>
Modernizr.load({
test: Modernizr.mq,
yep : alert("hello, beautiful"),
nope: alert("very poor choice of words"),
});
</script>
</body>
</html>
但它给了我yep
和nope
警报。
我不知道为什么,测试代码(如下)工作正常
if (Modernizr.mq("only screen and (min-width:480px)")) {
alert("hello");
};
有人可以告诉我我做错了吗?
答案 0 :(得分:1)
来自yepnopejs.com,“测试对象中有什么内容?!” :
yepnope([{
test : /* boolean(ish) - Something truthy that you want to test */,
yep : /* array (of strings) | string - The things to load if test is true */,
nope : /* array (of strings) | string - The things to load if test is false */,
both : /* array (of strings) | string - Load everytime (sugar) */,
load : /* array (of strings) | string - Load everytime (sugar) */,
callback : /* function ( testResult, key ) | object { key : fn } */,
complete : /* function */
}, ... ]);
所以在modernizr上(使用yepnope),yep需要一个字符串或一个字符串数组,你不能调用一个函数,所以如果你想根据浏览器是否支持媒体查询调用一个函数,你可以做:
if ( Modernizr.mq('only all') ){
alert("hello, beautiful"); // or
} else {
alert("very poor choice of words");
}
来自:http://modernizr.com/docs/#mq
修改强>
要在屏幕大小大于480px时运行一些js,你必须在窗口上监听resize事件,然后检查窗口的宽度然后运行你的代码,你不需要现代化的。例如(使用jquery):
(function($){
$(document).ready(function(){
$( window ).resize(function() {
var width = $( window ).width();
if ( width > 480){
alert("over 480"); // the js you want to run
}
});
});
})(jQuery);
不要忘记在此代码之前包含jquery。对不起,我无法发布到jquery resize()的链接,我达到了链接限制,我会在下面的评论上发布一个链接。干杯!