似乎无法获得jquery resize事件来处理Modernizr媒体查询功能

Ian*_*Ian 4 jquery resize modernizr

我正在尝试在以下函数上激活resize事件:

$(function() {
if (Modernizr.mq('only screen and (min-width: 1140px)')) {
$('div#ss1').html('<div>[snip]</div>');
$('div#ss1').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
  } 
if (Modernizr.mq('only screen and (max-width: 1139px)')) {
$('div#ss2').html('<div>[snip]</div>');
$('div#ss2').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
  } 
});
Run Code Online (Sandbox Code Playgroud)

我想为它添加一个resize监听器.基于http://api.jquery.com/resize/我将第一行更改为$(window).resize(function()但后来整个功能停止工作.

我究竟做错了什么?谢谢.

更新:根据Paul Irish的帖子,我将smartresize添加到我的plugins.js.我从改变函数调用$(function()$(window).smartresize(function()和它停止工作.将其更改回$(function()并再次起作用.为什么我不能向这个吸盘添加任何类型的resize事件监听器?:-)

nat*_*eta 9

这里要理解的关键点$(function() {})是做什么.在文档准备好之前,它内部的代码不会执行.将代码放入其中相当于将代码放入:

$(document).ready(function () { 
    //here 
})
Run Code Online (Sandbox Code Playgroud)

你想把你的resize事件放在里面$(function() {}),像这样:

function checkMq() {
    if (Modernizr.mq('only screen and (min-width: 1140px)')) {
        $('div#ss1').html('<div>[snip]</div>');
        $('div#ss1').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
    } 
    if (Modernizr.mq('only screen and (max-width: 1139px)')) {
        $('div#ss2').html('<div>[snip]</div>');
        $('div#ss2').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
    } 
}

$(function() {
    // the call to checkMq here will execute after the document has loaded
    checkMq();

    $(window).resize(function() {
        // the call to checkMq here will execute every time the window is resized
        checkMq();
    });

    // you can add other listeners here click, hover, etc.  
});
Run Code Online (Sandbox Code Playgroud)

如果您只是$(window).resize(function() {})没有使用$(function() {})它,它将无法工作,因为文档还没有准备好工作,也没有准备好添加任何事件监听器.