【问题标题】:Modernizr.load shows both yep and nope alertModernizr.load 显示是和否警报
【发布时间】:2014-01-06 23:45:44
【问题描述】:

我尝试了以下代码来测试 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");
};

谁能告诉我我做错了什么?

【问题讨论】:

    标签: modernizr yepnope


    【解决方案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                                                      */
    }, ... ]);
    

    so on 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 事件,然后检查窗口的宽度,然后运行你的代码,你不需要modernizr .例如(使用 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() 的链接,我已达到链接限制,我将在下面的 cmets 上发布链接。干杯!

    【讨论】:

    • 感谢fosfo的反馈,所以如果我想在屏幕尺寸大于480px时添加一些JS代码,我该如何实现呢?
    猜你喜欢
    • 2013-09-20
    • 2011-06-19
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多