我正在尝试使用 Modernizr 2 检测媒体查询是否存在,然后在适当的情况下加载到 respond.js 中。
我已将其放入我的 script.js 文件中...
Modernizr.load({
test: Modernizr.mq,
yep : '',
nope: 'mylibs/respond.js'
});
我做错了什么?我真的很惊讶 Modernizr 网站上没有如何使用媒体查询执行此操作的示例。这是我正在使用的 Modernizr 版本...
http://www.modernizr.com/download/#-backgroundsize-borderradius-boxshadow-iepp-respond-mq-cssclasses-teststyles-testprop-testallprops-prefixes-domprefixes-load
I'm trying to detect whether media queries are present using Modernizr 2, then loading in respond.js if appropriate.
I've put this in my script.js file...
Modernizr.load({
test: Modernizr.mq,
yep : '',
nope: 'mylibs/respond.js'
});
What am I doing wrong? I'm really surprised there isn't an example of how to do this with Media Queries on the Modernizr site. Here is the version of Modernizr I'm using...
http://www.modernizr.com/download/#-backgroundsize-borderradius-boxshadow-iepp-respond-mq-cssclasses-teststyles-testprop-testallprops-prefixes-domprefixes-load
发布评论
评论(2)
那是因为
!!Modernizr.mq === true
始终...您正在测试错误的东西!根据文档:
但是这个:
Modernizr.mq()
也是false
!你必须实际测试一些东西。在这里,all
关键字正是您所需要的(或者如 Paul 建议的那样only all
):但是,Modernizr 2.0.x 的所有自定义版本使用
mq
include respond.js,所以你永远不需要测试它,除非你想加载另一个polyfill。在这种情况下,您需要从构建中禁用/删除 respond.js。Modernizr 2.5.x
随着 Modernizr 2.5.x 的到来,上述情况不再成立。 缩写变更日志指定:
这意味着
Modernizr.mq('only all')
可能 现在返回false
...That's because
!!Modernizr.mq === true
at all times... you're testing for the wrong thing!As per the docs:
But this:
Modernizr.mq()
isfalse
too! You have to actually test for something. Here, theall
keyword is just what you need (oronly all
as Paul suggests):However, all custom builds of Modernizr 2.0.x with
mq
include respond.js, so you never really need to test this, except if you want to load another polyfill instead. In that case, you will need to disable/remove respond.js from your build.Modernizr 2.5.x
With the arrival of Modernizr 2.5.x, the above is no longer true. The abbreviated changelog specifies that:
This means
Modernizr.mq('only all')
may now returnfalse
...刚刚注意到菲利克斯答案的评论中得出了这个结论 -我将我的答案留在这里,以防它对像我一样没有得到答案的其他访问者有所帮助。
不确定这是否仍然是一个问题,但如果您正在加载 Modernizr v2.0.6,则不需要运行此测试。只需将其添加到您的页面就应该会自动启动 respond.js,并且您的媒体查询应该开始工作。
自从我在 IE8 中不断返回“true”以来,我也一直在为这个问题摸不着头脑! Modernizr 网站上的解释很差,但在 http://html5boilerplate.com/ (第一个实例)中提到
Just noticed this conclusion is reached in the comments of Felix's answer - I'm leaving my answer here in case it helps other visitors who, like me, did not get it.
Not sure if this is still an issue but if you are loading Modernizr v2.0.6 you shouldn't need to run this test. Just adding it to your page should automatically fire-up respond.js and your media queries should start working.
I've been scratching my head over this as well since I kept getting "true" returned in IE8!! Poorly explained on the Modernizr site but alluded to in the http://html5boilerplate.com/ (first instance)