如何使用jQuery创建“请稍候,正在加载...”动画?

我想在我的网站上放置一个“请稍等,加载中”的旋转圆圈动画。 我应该如何使用jQuery完成此操作?


#1楼

Jonathon的出色解决方案在IE8中中断(动画完全不显示)。 要解决此问题,请将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)};

#2楼

如果您使用带有Rails的Turbolinks,这是我的解决方案:

这是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;
}

#3楼

您可以从Ajaxload中获取旋转圆圈的GIF动画-将其粘贴在网站文件层次结构中的某个位置。 然后,您只需要添加带有正确代码的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();

这有一些警告:首先,如果您有两个或两个以上的位置可以显示正在加载的图像,则您将需要保持跟踪一次有多少个正在运行的呼叫,并且仅当它们正在运行时才隐藏全部做完。 可以使用一个简单的计数器完成此操作,该计数器几乎适用于所有情况。

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


#4楼

您可以通过各种不同的方式进行操作。 在页面上显示为“正在加载...”的小状态可能是微妙的,或者在加载新数据时整个页面变灰会使整个页面变灰。 我在下面采用的方法将向您展示如何完成这两种方法。

设置

让我们从我将要使用的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('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;
}

最后,jQuery

好了,到jQuery。 下一部分实际上非常简单:

$body = $("body");

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

而已! 每当ajaxStartajaxStop事件时,我们都会在body元素上附加一些事件。 当ajax事件开始时,我们将“ loading”类添加到正文中。 当事件完成后,我们从主体中删除“ loading”类。

实际运行中查看它: http : //jsfiddle.net/VpDUG/4952/


#5楼

jQuery为AJAX请求何时开始和结束提供事件挂钩。 您可以插入其中以显示您的装载机。

例如,创建以下div:

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

将其设置为display: none样式表中display: none 。 您可以按照自己的方式设置样式。 如果愿意,可以在Ajaxload.info上生成一个不错的加载图像。

然后,您可以使用以下类似的方法使它在发送Ajax请求时自动显示:

$(document).ready(function () {

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

});

只需关闭body标签或您认为合适的任何位置之前,将此Javascript块添加到页面的末尾即可。

现在,无论何时发送Ajax请求,都会显示#spinner div。 请求完成后,它将再次被隐藏。


#6楼

连同Jonathan和Samir的建议(两个都是很好的答案!),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();
 });

#7楼

就像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>

观察:我在http://www.ajaxload.info/上获得了ajax-loader.gif


#8楼

我见过的大多数解决方案都希望我们设计一个加载叠加层,将其隐藏起来,然后在需要时取消隐藏,或者显示gif或图像等。

我想开发一个功能强大的插件,通过一个简单的jQuery调用,我可以显示加载屏幕,并在任务完成时将其拆解。

下面是代码。 这取决于Font awesome和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();

#9楼

在充分尊重其他帖子的情况下,您在这里有一个非常简单的解决方案,使用CSS3和jQuery,无需使用任何其他外部资源或文件。

 $('#submit').click(function(){ $(this).addClass('button_loader').attr("value",""); window.setTimeout(function(){ $('#submit').removeClass('button_loader').attr("value","\✓"); $('#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" /> 


#10楼

我使用CSS3进行动画制作

 /************ 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> 


#11楼

请注意,使用ASP.Net MVC时, using (Ajax.BeginForm(... ,设置ajaxStart将不起作用。

使用AjaxOptions可以解决此问题:

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

#12楼

根据https://www.w3schools.com/howto/howto_css_loader.asp ,这是一个两步过程,没有JS:

1.在需要旋转器的位置添加以下HTML: <div class="loader"></div>

2.添加以下CSS来制作实际的微调器:

.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); }
}

#13楼

至于实际的加载图像, 请查看该站点的大量选项。

至于在请求开始时用此图像显示DIV,您有几种选择:

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

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

B)使用ajaxStartajaxComplete

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

使用此元素将显示/隐藏任何请求。 可能是好是坏,取决于需要。

C)对特定请求使用单独的回调:

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

#14楼

这将使按钮消失,然后在其位置出现“加载”动画,最后仅显示成功消息。

$(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>');
                    });
                }
        );
    });
});
发布了0 篇原创文章 · 获赞 1 · 访问量 2579

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/103893256