4

次の関数でサイズ変更イベントをアクティブにしようとしています:

$(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>');
  } 
});

それにサイズ変更リスナーを追加したかったのです。http://api.jquery.com/resize/に基づいて、最初の行をに変更しました$(window).resize(function()が、関数全体が機能しなくなりました。

私は何を間違っていますか?ありがとう。

更新: このポール アイリッシュの投稿に基づいて、smartresize を plugins.js に追加しました。関数呼び出しを から に変更したところ、機能し$(function()なく$(window).smartresize(function()なりました。それを元に戻すと$(function()、再び機能しました。どのタイプのサイズ変更イベント リスナーもこの吸盤に追加できないのはなぜですか? :-)

4

1 に答える 1

9

ここで理解すべき重要な点は、何をしているのか$(function() {})です。その中のコードは、ドキュメントの準備が整うまで実行されません。そこにコードを入れることは、これにコードを入れることと同じです:

$(document).ready(function () { 
    //here 
})

次のように、サイズ変更イベントを の中に入れます$(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.  
});

$(window).resize(function() {})を使用せずに を持っているだけでは$(function() {})、ドキュメントはまだ作業する準備ができておらず、イベント リスナーを追加する準備ができていないため、機能しません。

于 2013-05-01T06:56:56.260 に答える