jQuery を使用して「お待ちください、ロード中...」アニメーションを作成するにはどうすればよいでしょうか? 質問する

jQuery を使用して「お待ちください、ロード中...」アニメーションを作成するにはどうすればよいでしょうか? 質問する

「お待ちください、ロード中」という回転する円のアニメーションを自分のサイトに配置したいのですが、jQuery を使用してこれを実現するにはどうすればよいでしょうか?

ベストアンサー1

これにはさまざまな方法があります。ページ上に「読み込み中...」という小さなステータスを表示するなど、控えめな方法もあれば、新しいデータの読み込み中にページの要素全体をグレー表示するなど、派手な方法もあります。以下で紹介するアプローチでは、両方の方法を実現する方法を説明します。

セットアップ

まずは、素敵な「読み込み」アニメーションを用意しましょう。http://ajaxload.info私は使いますここに画像の説明を入力してください

Ajax リクエストを行うときにいつでも表示/非表示にできる要素を作成しましょう。

<div class="modal"><!-- Place at bottom of page --></div>

CSS

次に、少し趣向を加えてみましょう。

/* Start by setting display:none to make this hidden.
   Then we position it in relation to the viewport window
   with position:fixed. Width, height, top and left speak
   for themselves. Background we set to 80% white with
   our animation centered, and no-repeating */
.modal {
    display:    none;
    position:   fixed;
    z-index:    1000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .8 ) 
                url('https://i.sstatic.net/FhHRx.gif') 
                50% 50% 
                no-repeat;
}

/* When the body has the loading class, we turn
   the scrollbar off with overflow:hidden */
body.loading .modal {
    overflow: hidden;   
}

/* Anytime the body has the loading class, our
   modal element will be visible */
body.loading .modal {
    display: block;
}

そして最後に、jQuery

さて、jQuery に移りましょう。次の部分は実に簡単です。

$body = $("body");

$(document).on({
    ajaxStart: function() { $body.addClass("loading");    },
     ajaxStop: function() { $body.removeClass("loading"); }    
});

ajaxStartこれで完了です。またはイベントが発生するたびに、いくつかのイベントを body 要素にアタッチしますajaxStop。Ajax イベントが開始されると、body に「loading」クラスが追加されます。イベントが完了すると、body から「loading」クラスが削除されます。

実際に動作を見てみましょう:http://jsfiddle.net/VpDUG/4952/

おすすめ記事