Como posso criar uma animação "por favor, espere, carregue ..." usando o jQuery?
14 answers
A Configuração
Vamos começar por arranjar uma boa animação de "carregar" de http://ajaxload.info Eu terei usado Vamos criar um elemento que possamos mostrar/esconder a qualquer momento estamos a fazer um pedido ajax.<div class="modal"><!-- Place at bottom of page --></div>
O CSS
A seguir, vamos dar-lhe um toque especial./* 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 .modal {
overflow: hidden;
}
/* Anytime the body has the loading class, our
modal element will be visible */
body.loading .modal {
display: block;
}
E finalmente, o jQuery.
Muito bem, vamos ao jQuery. Esta próxima parte é realmente muito simples:
$body = $("body");
$(document).on({
ajaxStart: function() { $body.addClass("loading"); },
ajaxStop: function() { $body.removeClass("loading"); }
});
É isso! Estamos a ligar alguns eventos ao elemento do corpo quando os eventos forem disparados. Quando um evento ajax começa, adicionamos a classe "carregamento" ao corpo. e quando os eventos são feitos, removemos a classe "carregamento" do corpo.
Vê. em acção: http://jsfiddle.net/VpDUG/4952/
Quanto à imagem de carregamento actual, Verifique este site para um monte de opções.
Quanto a mostrar um DIV com esta imagem quando um pedido começa, você tem algumas opções:
A) mostrar e esconder manualmente a imagem:
$('#form').submit(function() {
$('#wait').show();
$.post('/whatever.php', function() {
$('#wait').hide();
});
return false;
});
B) utilizar ajaxStart e ajaxComplete:
$('#wait').ajaxStart(function() {
$(this).show();
}).ajaxComplete(function() {
$(this).hide();
});
Se usar isto, o elemento irá mostrar / esconder para qualquer pedido. Pode ser bom ou mau, dependendo da necessidade.
C) utilizar callbacks individuais para um pedido específico:
$('#form').submit(function() {
$.ajax({
url: '/whatever.php',
beforeSend: function() { $('#wait').show(); },
complete: function() { $('#wait').hide(); }
});
return false;
});
ajaxStart
evento
Mostra uma mensagem de carregamento sempre que um pedido do AJAX começa (e nenhum já está activo).
...e é o irmão, o ajaxStop
evento
Juntos, eles fazem uma ótima maneira de mostrar uma mensagem de progresso quando qualquer atividade ajax está acontecendo em qualquer lugar da página.Anexar uma função a ser executada sempre que todos os pedidos do AJAX tiverem terminado. Isto é um Ajax. Evento.
HTML:
<div id="loading">
<p><img src="loading.gif" /> Please Wait</p>
</div>
Script:
$(document).ajaxStart(function(){
$('#loading').show();
}).ajaxStop(function(){
$('#loading').hide();
});
function showLoadingImage() {
$('#yourParentElement').append('<div id="loading-image"><img src="path/to/loading.gif" alt="Loading..." /></div>');
}
function hideLoadingImage() {
$('#loading-image').remove();
}
Você só precisa de usar estes métodos na sua chamada 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();
Isto tem algumas ressalvas: em primeiro lugar, se você tem dois ou mais lugares que a imagem de carregamento pode ser mostrado, você vai precisar de Kep track de como muitas chamadas estão a ser feitas ao mesmo tempo, e só se escondem quando terminarem. Isto pode ser feito usando um contador simples, que deve funcionar para quase todos os casos.
Em segundo lugar, isto só irá esconder a imagem de carregamento numa chamada AJAX bem sucedida. Para lidar com os estados de erro, você terá que olhar para $.ajax
, o que é mais complexo do que $.load
, $.get
e assim, mas muito mais flexível também.
A excelente solução de Jonathon quebra no IE8 (a animação não aparece de todo). Para corrigir isso, mude o CSS para:
.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)};
Por exemplo, crie o seguinte div:
<div id="spinner">
<img src="images/spinner.gif" alt="Loading" />
</div>
Configure-o para display: none
nas suas folhas de estilo. Podes usá-lo como quiseres. Você pode gerar uma boa imagem de carregamento em Ajaxload.info , Se quiseres.
Então, você pode usar algo como o seguinte para fazê-lo ser mostrado automaticamente ao enviar Ajax pedidos:
$(document).ready(function () {
$('#spinner').bind("ajaxSend", function() {
$(this).show();
}).bind("ajaxComplete", function() {
$(this).hide();
});
});
Basta adicionar este bloco de Javascript ao fim da sua Página Antes de fechar a sua marca corporal ou onde quiser.
Agora, sempre que você enviar pedidos Ajax, o div#spinner
será mostrado. Quando o pedido estiver completo, estará escondido novamente.
Se está a usar Turbolinks com Carris esta é a minha solução:
Este é o CoffeeScript.$(window).on 'page:fetch', ->
$('body').append("<div class='modal'></div>")
$('body').addClass("loading")
$(window).on 'page:change', ->
$('body').removeClass("loading")
Esta é a SASS CSS baseada na primeira excelente resposta de Jonathan Sampson.
# 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;
}
Ex.:
<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. Eu tenho o carregador ajax.gif on http://www.ajaxload.info/
Com todo o respeito devido a outros posts, você tem aqui uma solução muito simples, usando CSS3 e jQuery, sem usar mais recursos externos nem arquivos.
$('#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" />
Note que ao utilizar asp.net mvc, com " using (Ajax.BeginForm (..."definir o" ajaxStart " não vai funcionar.
Use as ajaxotions para superar este problema:
(Ajax.BeginForm("ActionName", new AjaxOptions { OnBegin = "uiOfProccessingAjaxAction", OnComplete = "uiOfProccessingAjaxActionComplete" }))
$(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>');
});
}
);
});
});
A maioria das soluções que vi ou esperam que desenhemos uma sobreposição de carga, que a mantenhamos escondida e depois a libertemos quando necessário, ou que mostremos um gif ou imagem, etc.
Eu queria desenvolver um plugin robusto onde com uma simples chamada jQuery eu posso exibir o ecrã de carregamento e derrubá-lo quando a tarefa é concluída.
Abaixo está o código. Depende da fonte incrível e do 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));
Basta colocar o acima em um arquivo js e incluí-lo em todo o projecto.
Invocação:
$.loadingSpinner();
$.removeLoadingSpinner();
Por https://www.w3schools.com/howto/howto_css_loader.asp , Este é um processo de 2 etapas sem JS:
1.Adicionar este HTML onde deseja o spinner: <div class="loader"></div>
2.Adicione este CSS para fazer o spinner actual:
.loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
USO o CSS3 para a animação
/************ CSS3 *************/
.icon-spin {
font-size: 1.5em;
display: inline-block;
animation: spin1 2s infinite linear;
}
@keyframes spin1{
0%{transform:rotate(0deg)}
100%{transform:rotate(359deg)}
}
/************** CSS3 cross-platform ******************/
.icon-spin-cross-platform {
font-size: 1.5em;
display: inline-block;
-moz-animation: spin 2s infinite linear;
-o-animation: spin 2s infinite linear;
-webkit-animation: spin 2s infinite linear;
animation: spin2 2s infinite linear;
}
@keyframes spin2{
0%{transform:rotate(0deg)}
100%{transform:rotate(359deg)}
}
@-moz-keyframes spin2{
0%{-moz-transform:rotate(0deg)}
100%{-moz-transform:rotate(359deg)}
}
@-webkit-keyframes spin2{
0%{-webkit-transform:rotate(0deg)}
100%{-webkit-transform:rotate(359deg)}
}
@-o-keyframes spin2{
0%{-o-transform:rotate(0deg)}
100%{-o-transform:rotate(359deg)}
}
@-ms-keyframes spin2{
0%{-ms-transform:rotate(0deg)}
100%{-ms-transform:rotate(359deg)}
}
<link href="https://maxcdn.bootstrapcdn.com/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>