如何使用jQuery创build“Please Wait,Loading …”animation?

我想在我的网站上放置一个“请稍候,加载”旋转圈animation。 我应该如何使用jQuery来完成这个任务?

你可以做这个不同的方式。 它可能是一个微小的页面上的一个小的状态,说“正在加载…”,或者像新的数据加载时整个元素灰色的页面一样大声。 我正在采取的方法将告诉你如何完成这两种方法。

安装程序

首先让我们从http://ajaxload.info获取一个很好的“加载”animation,我将使用它; 在这里输入图像描述

让我们创build一个元素,我们可以显示/隐藏任何时候我们正在做一个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('http://i.stack.imgur.com/FhHRx.gif') 50% 50% no-repeat; } /* When the body has the loading class, we turn the scrollbar off with overflow:hidden */ body.loading { 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"); } }); 

而已! 只要ajaxStartajaxStop事件触发,我们就会将一些事件附加到body元素。 当ajax事件开始时,我们将“加载”类添加到正文。 当事件完成时,我们从正文中删除“加载”类。

看到它的行动: http : //jsfiddle.net/VpDUG/4952/

至于实际的加载图片, 请查看本网站的一堆选项。

至于在请求开始时用这个图像显示一个DIV,你有几个select:

A)手动显示和隐藏图像:

 $('#form').submit(function() { $('#wait').show(); $.post('/whatever.php', function() { $('#wait').hide(); }); return false; }); 

B)使用ajaxStart和ajaxComplete :

 $('#wait').ajaxStart(function() { $(this).show(); }).ajaxComplete(function() { $(this).hide(); }); 

使用这个元素将显示/隐藏任何请求。 根据需要可能是好还是坏。

C)针对特定的请求使用单独的callback:

 $('#form').submit(function() { $.ajax({ url: '/whatever.php', beforeSend: function() { $('#wait').show(); }, complete: function() { $('#wait').hide(); } }); return false; }); 

随着乔纳森和萨米尔build议(两个优秀的答案btw!),jQuery有一些内置的事件,它会在你发出ajax请求时触发。

ajaxStart事件

每当一个AJAX请求开始时显示一个加载消息(而没有一个已经激活)。

…这是兄弟, ajaxStop事件

附加一个函数,当所有的AJAX请求结束时执行。 这是一个Ajax事件。

总之,当页面上的任何地方发生任何ajax活动时,它们都可以很好地显示进度信息。

HTML:

 <div id="loading"> <p><img src="loading.gif" /> Please Wait</p> </div> 

脚本:

 $(document).ajaxStart(function(){ $('#loading').show(); }).ajaxStop(function(){ $('#loading').hide(); }); 

你可以从Ajaxload抓取一个旋转圈的animationGIF – 在你的网站文件的某个地方粘贴。 然后你只需要添加一个正确的代码的HTML元素,并完成后删除它。 这很简单:

 function showLoadingImage() { $('#yourParentElement').append('<div id="loading-image"><img src="path/to/loading.gif" alt="Loading..." /></div>'); } function hideLoadingImage() { $('#loading-image').remove(); } 

然后你只需要在你的AJAX调用中使用这些方法:

 $.load( 'http://example.com/myurl', { 'random': 'data': 1: 2, 'dwarfs': 7}, function (responseText, textStatus, XMLHttpRequest) { hideLoadingImage(); } ); // this will be run immediately after the AJAX call has been made, // not when it completes. showLoadingImage(); 

这有几点注意事项:首先,如果你有两个或两个以上的地方加载图像可以显示,你将需要跟踪多less次调用一次运行,只有当他们隐藏全做完了。 这可以使用一个简单的计数器来完成,它几乎适用于所有情况。

其次,这只会隐藏成功的AJAX调用加载图像。 为了处理错误状态,您需要查看$.ajax ,它比$.load$.get等更复杂,但是也更加灵活。

乔纳森杰出的解决scheme在IE8中破解(animation根本不显示)。 要解决这个问题,请将CSS更改为:

 .modal { display: none; position: fixed; z-index: 1000; top: 0; left: 0; height: 100%; width: 100%; background: rgba( 255, 255, 255, .8 ) url('http://i.stack.imgur.com/FhHRx.gif') 50% 50% no-repeat; opacity: 0.80; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity = 80); filter: alpha(opacity = 80)}; 

jQuery为AJAX请求的开始和结束提供了事件挂钩。 你可以勾上这些来显示你的装载机。

例如,创build以下div:

 <div id="spinner"> <img src="images/spinner.gif" alt="Loading" /> </div> 

将其设置为在样式表中display: none 。 你可以用任何你想要的方式来devise它。 如果你愿意的话 ,你可以在Ajaxload.info生成一个漂亮的加载图片。

然后,当发送Ajax请求时,可以使用类似下面的内容来使其自动显示:

 $(document).ready(function () { $('#spinner').bind("ajaxSend", function() { $(this).show(); }).bind("ajaxComplete", function() { $(this).hide(); }); }); 

只需closures您的身体标记或任何您认为合适的地方添加此JavaScript块到您的页面的末尾。

现在,只要您发送Ajax请求,就会显示#spinner div。 请求完成后,将再次隐藏。

如果你使用Turbolinks With Rails,这是我的解决scheme:

这是CoffeeScript

 $(window).on 'page:fetch', -> $('body').append("<div class='modal'></div>") $('body').addClass("loading") $(window).on 'page:change', -> $('body').removeClass("loading") 

这是基于乔纳森·桑普森(Jonathan Sampson)的第一个杰出答案的SASS CSS

 # loader.css.scss .modal { display: none; position: fixed; z-index: 1000; top: 0; left: 0; height: 100%; width: 100%; background: rgba( 255, 255, 255, 0.4) asset-url('ajax-loader.gif', image) 50% 50% no-repeat; } body.loading { overflow: hidden; } body.loading .modal { display: block; } 

像Mark H说的那样,blockUI就是这样。

例:

 <script type="text/javascript" src="javascript/jquery/jquery.blockUI.js"></script> <script> // unblock when ajax activity stops $(document).ajaxStop($.unblockUI); $("#downloadButton").click(function() { $("#dialog").dialog({ width:"390px", modal:true, buttons: { "OK, AGUARDO O E-MAIL!": function() { $.blockUI({ message: '<img src="img/ajax-loader.gif" />' }); send(); } } }); }); function send() { $.ajax({ url: "download-enviar.do", type: "POST", blablabla }); } </script> 

Obs .:我在http://www.ajaxload.info/上find了ajax-loader.gif

注意,当使用asp.net mvc时,“使用(Ajax.BeginForm(…)”设置“ajaxStart”将不起作用。

使用ajaxotions来解决这个问题:

 (Ajax.BeginForm("ActionName", new AjaxOptions { OnBegin = "uiOfProccessingAjaxAction", OnComplete = "uiOfProccessingAjaxActionComplete" })) 

这将使button消失,然后一个“加载”的animation会出现在他们的位置,最后只是显示一个成功的消息。

 $(function(){ $('#submit').click(function(){ $('#submit').hide(); $("#form .buttons").append('<img src="assets/img/loading.gif" alt="Loading..." id="loading" />'); $.post("sendmail.php", {emailFrom: nameVal, subject: subjectVal, message: messageVal}, function(data){ jQuery("#form").slideUp("normal", function() { $("#form").before('<h1>Success</h1><p>Your email was sent.</p>'); }); } ); }); }); 

有了其他职位的尊重,你在这里有一个非常简单的解决scheme,使用CSS3和jQuery,而不使用任何进一步的外部资源和文件。

 $('#submit').click(function(){ $(this).addClass('button_loader').attr("value",""); window.setTimeout(function(){ $('#submit').removeClass('button_loader').attr("value","\u2713"); $('#submit').prop('disabled', true); }, 3000); }); 
 #submit:focus{ outline:none; outline-offset: none; } .button { display: inline-block; padding: 6px 12px; margin: 20px 8px; font-size: 14px; font-weight: 400; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; background-image: none; border: 2px solid transparent; border-radius: 5px; color: #000; background-color: #b2b2b2; border-color: #969696; } .button_loader { background-color: transparent; border: 4px solid #f3f3f3; border-radius: 50%; border-top: 4px solid #969696; border-bottom: 4px solid #969696; width: 35px; height: 35px; -webkit-animation: spin 0.8s linear infinite; animation: spin 0.8s linear infinite; } @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 99% { -webkit-transform: rotate(360deg); } } @keyframes spin { 0% { transform: rotate(0deg); } 99% { transform: rotate(360deg); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="submit" class="button" type="submit" value="Submit" /> 

我所看到的大多数解决scheme要么devise一个加载覆盖,保持隐藏,然后在需要时取消隐藏,或者显示gif或图像等。

我想开发一个健壮的插件,只需简单的jQuery调用,我可以显示加载屏幕,并在任务完成时将其撕下。

下面是代码。 这取决于字体真棒和jQuery:

 /** * Raj: Used basic sources from here: http://jsfiddle.net/eys3d/741/ **/ (function($){ // Retain count concept: http://stackoverflow.com/a/2420247/260665 // Callers should make sure that for every invocation of loadingSpinner method there has to be an equivalent invocation of removeLoadingSpinner var retainCount = 0; // http://stackoverflow.com/a/13992290/260665 difference between $.fn.extend and $.extend $.extend({ loadingSpinner: function() { // add the overlay with loading image to the page var over = '<div id="custom-loading-overlay">' + '<i id="custom-loading" class="fa fa-spinner fa-spin fa-3x fa-fw" style="font-size:48px; color: #470A68;"></i>'+ '</div>'; if (0===retainCount) { $(over).appendTo('body'); } retainCount++; }, removeLoadingSpinner: function() { retainCount--; if (retainCount<=0) { $('#custom-loading-overlay').remove(); retainCount = 0; } } }); }(jQuery)); 

只要把上面的一个js文件,并将其包括在整个项目。

调用:

 $.loadingSpinner(); $.removeLoadingSpinner(); 

我使用CSS3进行animation

 .icon-spin { display: inline-block; animation: spin 2s infinite linear; } .icon-spin-cross-platform { display: inline-block; -moz-animation: spin 2s infinite linear; -o-animation: spin 2s infinite linear; -webkit-animation: spin 2s infinite linear; animation: spin 2s infinite linear; } @-moz-keyframes spin{ 0%{-moz-transform:rotate(0deg)} 100%{-moz-transform:rotate(359deg)} } @-webkit-keyframes spin{ 0%{-webkit-transform:rotate(0deg)} 100%{-webkit-transform:rotate(359deg)} } @-o-keyframes spin{ 0%{-o-transform:rotate(0deg)} 100%{-o-transform:rotate(359deg)} } @-ms-keyframes spin{ 0%{-ms-transform:rotate(0deg)} 100%{-ms-transform:rotate(359deg)} } @keyframes spin{ 0%{transform:rotate(0deg)} 100%{transform:rotate(359deg)} } 
 <link href="bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <div class="row"> <div class="col-md-6"> Default CSS3 <span class="glyphicon glyphicon-repeat icon-spin"></span> </div> <div class="col-md-6"> Cross-Platform CSS3 <span class="glyphicon glyphicon-repeat icon-spin-cross-platform"></span> </div> </div>