2011-10-23 121 views
1

我包括Modernizr的在我的网站:Modernizr媒体查询不起作用?

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/modernizr.custom.js"></script> 

,我有这custom.js

if (Modernizr.mq("screen and (max-width:480)")) { 
alert("hello"); 
} 

我调整我的浏览器是480像素,刷新网站,但我没有”没有看到任何警报。

任何建议来解决这个问题?

回答

5

您需要的单位值px在媒体查询:

你行:

if (Modernizr.mq("screen and (max-width:480)")) {\ 

应该是:

if (Modernizr.mq("screen and (max-width:480px)")) { 
+0

感谢是一个错字。 – alexchenco

1

韦斯利是正确的,但只是一个快速注记是if (Modernizr.mq("screen and (max-width:480px)")) {仍然只会触发,如果媒体查询条件满足!

所以如果你的屏幕大于480px并且这个脚本被调用,它将不会提醒。

这只是今天创建触发脚本时,媒体查询是触发(用IE后备):

  //Test to see if media queries are acceptable 
      if(Modernizr.mq('only all')){ 
       var mql = window.matchMedia('(max-width: 980px)'); 

       mql.addListener(tabletChange); 
       tabletChange(mql); 

       function tabletChange(mediaQueryList) { 
        //If media query triggered 
        if (mediaQueryList.matches) {  
         //SMALL SCREEN 
        } else { 
         //LARGE SCREEN 
        } 
       } 

      } else { 

       var resizeTimer; 
       mediaMatchFallback(); 

       $(window).resize(function(){ 
        if(resizeTimer){ 
         clearTimeout(resizeTimer); 
        } 
        resizeTimer = setTimeout(mediaMatchFallback, 500); 
       }); 

       function mediaMatchFallback(){ 
        if($(window).width() <= 980){ 
         //SMALL SCREEN 
        }else{ 
         //LARGE SCREEN 
        } 
       } 
      }