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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1964839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:29:11  来源:igfitidea点击:

How can I create a "Please Wait, Loading..." animation using jQuery?

jqueryanimation

提问by thedp

I would like to place a "please wait, loading" spinning circle animation on my site. How should I accomplish this using jQuery?

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

回答by Sampson

You could do this various different ways. It could be a subtle as a small status on the page saying "Loading...", or as loud as an entire element graying out the page while the new data is loading. The approach I'm taking below will show you how to accomplish both methods.

你可以用各种不同的方式来做到这一点。它可能是微妙的,比如页面上的一个小状态说“正在加载...”,或者像在加载新数据时整个元素使页面变灰一样响亮。我在下面采用的方法将向您展示如何完成这两种方法。

The Setup

设置

Let's start by getting us a nice "loading" animation from http://ajaxload.infoI'll be using enter image description here

让我们从http://ajaxload.info 为我们提供一个很好的“加载”动画开始, 我将使用在此处输入图片说明

Let's create an element that we can show/hide anytime we're making an ajax request:

让我们创建一个可以在任何时候发出 ajax 请求时显示/隐藏的元素:

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

The CSS

CSS

Next let's give it some flair:

接下来让我们给它一些天赋:

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

And finally, the jQuery

最后,jQuery

Alright, on to the jQuery. This next part is actually really simple:

好的,继续使用 jQuery。下一部分实际上非常简单:

$body = $("body");

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

That's it! We're attaching some events to the body element anytime the ajaxStartor ajaxStopevents are fired. When an ajax event starts, we add the "loading" class to the body. and when events are done, we remove the "loading" class from the body.

就是这样!我们在触发ajaxStartajaxStop事件时将一些事件附加到 body 元素。当 ajax 事件开始时,我们将“加载”类添加到主体中。当事件完成时,我们从主体中删除“加载”类。

See it in action: http://jsfiddle.net/VpDUG/4952/

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

回答by Paolo Bergantino

As far as the actual loading image, check out this sitefor a bunch of options.

至于实际加载图像,请查看此站点以获取大量选项。

As far as displaying a DIV with this image when a request begins, you have a few choices:

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

A) Manually show and hide the image:

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

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

B) Use ajaxStartand ajaxComplete:

B) 使用ajaxStartajaxComplete

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

Using this the element will show/hide for anyrequest. Could be good or bad, depending on the need.

使用此元素将显示/隐藏任何请求。可好可坏,视需要而定。

C) Use individual callbacks for a particular request:

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

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

回答by Dan F

Along with what Jonathan and Samir suggested (both excellent answers btw!), jQuery has some built in events that it'll fire for you when making an ajax request.

除了 Jonathan 和 Samir 建议的内容(顺便说一句,这两个都是很好的答案!),jQuery 有一些内置事件,在发出 ajax 请求时会触发这些事件。

There's the ajaxStartevent

ajaxStart活动

Show a loading message whenever an AJAX request starts (and none is already active).

每当 AJAX 请求开始时显示加载消息(并且没有一个已经处于活动状态)。

...and it's brother, the ajaxStopevent

...这是兄弟,ajaxStop事件

Attach a function to be executed whenever all AJAX requests have ended. This is an Ajax Event.

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

Together, they make a fine way to show a progress message when any ajax activity is happening anywhere on the page.

当页面上的任何地方发生任何 ajax 活动时,它们一起提供了一种显示进度消息的好方法。

HTML:

HTML:

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

Script:

脚本:

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

回答by Samir Talwar

You can grab an animated GIF of a spinning circle from Ajaxload- stick that somewhere in your website file heirarchy. Then you just need to add an HTML element with the correct code, and remove it when you're done. This is fairly simple:

您可以从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();
}

You then just need to use these methods in your AJAX call:

然后你只需要在你的 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();

This has a few caveats: first of all, if you have two or more places the loading image can be shown, you're going to need to kep track of how many calls are running at once somehow, and only hide when they're all done. This can be done using a simple counter, which should work for almost all cases.

这有一些警告:首先,如果您有两个或更多可以显示加载图像的位置,您将需要以某种方式跟踪同时运行的调用数量,并且仅在它们出现时隐藏全部完成。这可以使用一个简单的计数器来完成,它几乎适用于所有情况。

Secondly, this will only hide the loading image on a successful AJAX call. To handle the error states, you'll need to look into $.ajax, which is more complex than $.load, $.getand the like, but a lot more flexible too.

其次,这只会在成功的 AJAX 调用中隐藏加载图像。为了处理错误状态,你需要考虑$.ajax,这是比较复杂$.load$.get之类的,但很多更灵活了。

回答by Ben Power

Jonathon's excellent solution breaks in IE8 (the animation does not show at all). To fix this, change the CSS to:

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

回答by Fred

If you are using Turbolinks With Rails this is my solution:

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

This is the CoffeeScript

这是 CoffeeScript

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

$(window).on 'page:change', ->
  $('body').removeClass("loading")

This is the SASS CSS based on the first excellent answer from Jonathan Sampson

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

回答by Veeti

jQuery provides event hooks for when AJAX requests start and end. You can hook into these to show your loader.

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

For example, create the following div:

例如,创建以下 div:

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

Set it to display: nonein your stylesheets. You can style it whatever way you want to. You can generate a nice loading image at Ajaxload.info, if you want to.

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

Then, you can use something like the following to make it be shown automatically when sending Ajax requests:

然后,您可以使用如下所示的内容使其在发送 Ajax 请求时自动显示:

$(document).ready(function () {

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

});

Simply add this Javascript block to the end of your page beforeclosing your body tag or wherever you see fit.

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

Now, whenever you send Ajax requests, the #spinnerdiv will be shown. When the request is complete, it'll be hidden again.

现在,每当您发送 Ajax 请求时,#spinner都会显示 div。请求完成后,它将再次隐藏。

回答by bpedroso

Like Mark H said the blockUI is the way.

就像 Mark H 所说的 blockUI 就是这样。

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.: I got the ajax-loader.gif on http://www.ajaxload.info/

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

回答by Jo?o Pimentel Ferreira

With all due respect to other posts, you have here a very simple solution, using CSS3 and jQuery, without using any further external resources nor files.

尊重其他帖子,您在这里有一个非常简单的解决方案,使用 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" />

回答by Raj Pawan Gumdal

Most of the solutions I have seen either expects us to design a loading overlay, keep it hidden and then unhide it when required, or, show a gif or image etc.

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

I wanted to develop a robust plugin, where with a simply jQuery call I can display the loading screen and tear it down when the task is completed.

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

Below is the code. It depends on Font awesome and 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)); 

Just put the above in a js file and include it throughout the project.

只需将上述内容放在一个 js 文件中,并将其包含在整个项目中。

CSS addition:

CSS添加:

#custom-loading-overlay {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    background: #000;
    opacity: 0.8;
    filter: alpha(opacity=80);
}
#custom-loading {
    width: 50px;
    height: 57px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -28px 0 0 -25px;
}

Invocation:

调用:

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