首页 文章

如何使用jQuery创建“Please Wait,Loading ...”动画?

提问于
浏览
523

我想在我的网站上放置一个“请等待,加载”旋转圈动画 . 我应该如何使用jQuery实现这一目标?

14 回答

  • 1114

    根据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); }
    }
    
  • 104

    你可以用不同的方式做到这一点 . 它可能是一个微妙的页面上的小状态,表示“正在加载......”,或者在加载新数据时整个元素变灰的情况下变得很大 . 我在下面介绍的方法将向您展示如何完成这两种方法 .

    设置

    让我们从http://ajaxload.info给我们一个很好的"loading"动画开始我将使用
    enter image description here

    让我们创建一个元素,我们可以在制作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 事件被触发,'s it! We'就会将一些事件附加到body元素 . 当ajax事件开始时,我们将"loading"类添加到正文中 . 当事件完成后,我们从正文中删除"loading"类 .

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

  • 5

    我见过的大多数解决方案都要求我们设计加载叠加层,保持隐藏状态,然后在需要时取消隐藏,或者显示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();
    
  • 201

    你可以从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 等更复杂,但也要灵活得多 .

  • 5

    我使用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>
    
  • 17

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

  • 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();
     });
    
  • 3

    jQuery为AJAX请求的开始和结束提供事件挂钩 . 你可以挂钩来展示你的装载机 .

    例如,创建以下div:

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

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

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

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

    只需将此Javascript块添加到页面末尾 before 关闭您的身体标签或您认为合适的地方 .

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

  • 14

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

    使用 AjaxOptions 来克服此问题:

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

    至于实际加载图像,check out this site为一堆选项 .

    至于在请求开始时使用此图像显示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;
    });
    
  • 3

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

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

    这是CoffeeScript

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

    这是基于SASS的CSSJonathan 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;
    }
    
  • 1

    这将使按钮消失,然后在他们的位置出现“加载”动画,最后只显示成功消息 .

    $(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>');
                        });
                    }
            );
        });
    });
    
  • 3

    尽管如此,您还可以使用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" />
    

相关问题