2011-10-23 122 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 
        } 
       } 
      }