2

プリロードされたいくつかの大きな画像を含む Ajax ページがあります。読み込み中のメッセージを含む div を表示し、すべての画像が読み込まれたときにフェードアウトする必要があると感じています。現在、私はこのコードを使用しています:

$(function () {

    $(window).load(function () {
        $('#images-loading').css({
            visibility: 'hidden'
        })
            .fadeTo(200, function () {
        });
    });

});

HTML は単にページに配置されます<div id="images-loading"></div>が、機能しません。その理由は完全にはわかりません。機能しないということは、フェードアウトしないということです。そのままです。スクリプトは実際の ajax コンテンツ自体に配置されていると言わざるを得ませんが、ページが更新されたときにのみ起動されます。私はこれを自分で解決する経験が不足しているので、何か提案や試してみることができる代替案をいただければ幸いです。

4

2 に答える 2

1

画像の読み込みをローカルで確認したい場合は、すべてのimg要素をトラバースしてそれらのイベントを確認するか、 waitForImagesloadなどのプラグインを使用できます(免責事項: 私が作成しました)。

成功のコールバックでは、単純に...

$imagesLoading = $('#images-loading');

$imagesLoading.show();

$("#container").waitForImages(function() {
    $imagesLoading.fadeOut(200);
});
于 2012-09-26T00:42:22.867 に答える
0

現在、あなたはいくつかの小さなことを間違っています:

/// this first line basically says run my contents when the DOM is ready
$(function () {
  /// this second line says run my contents when the window is fully loaded
  /// but you are enabling this only after the DOM has loaded. Depending on
  /// the browser these two events can fire in either order so you may find
  /// situations where nothing would happen.
  $(window).load(function () {
    /// then you hide your image div
    $('#images-loading').css({
        visibility: 'hidden'
    })
    /// but then ask it to fade in
        .fadeTo(200, function () {
    });
  });
});

上記をより良い方法で書くと、次のようになります。

/// once the page has fully loaded - i.e. everything including
/// images is ready - then hide our loading message. Set this
/// listener first as it could fire at any time.
$(window).load(function () {
  $('#images-loading').stop().fadeOut(200);
});

/// as soon as the DOM is ready, show our loading message
/// the DOM event should fire before window load
$(function(){
  /// if you are learning it is far better to name your functions
  /// and then reference them where they are needed. It makes things
  /// easier to read.
  function whenFadeIsComplete(){
    alert('fade in complete');
  }
  /// rather than hide with setting style directly, use jQuery's own hide 
  /// function. Better still, use a CSS class directly on your #images-loading
  /// element that implements `display:none;` or `opacity:0;` - this will 
  /// render more quickly than JavaScript and mean you avoid your 
  /// loading div flickering into view before the fade in starts.
  $('#images-loading').hide().fadeTo(200, whenFadeIsComplete);
})

上記を試すと、ページを強制的に更新したときにのみ機能するという問題が解決する場合があります。ただし、画像がブラウザにキャッシュされている場合は、読み込み中のメッセージが表示されないことがあります(ページの読み込みが速すぎるため)。ブラウザを強制的に更新すると、(ほとんどのブラウザで)キャッシュがクリアされ、メッセージが表示されます。再び表示する時間。

于 2012-09-26T01:13:32.453 に答える