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

发布于 2024-08-16 20:08:27 字数 57 浏览 1 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

围归者 2024-08-23 20:08:27

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

设置

首先让我们从 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('https://i.sstatic.net/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”类添加到正文中。当事件完成时,我们从主体中删除“正在加载”类。

查看实际操作:http://jsfiddle.net/VpDUG/4952/

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.info
I'll be using enter image description here

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

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

The 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('https://i.sstatic.net/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

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

$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 ajaxStart or ajaxStop events 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.

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

魄砕の薆 2024-08-23 20:08:27

至于实际加载图像,查看此网站以获取一系列选项。

至于在请求开始时显示带有此图像的 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;
});

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

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

A) Manually show and hide the image:

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

B) Use ajaxStart and ajaxComplete:

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

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

C) Use individual callbacks for a particular request:

$('#form').submit(function() {
    $.ajax({
        url: '/whatever.php',
        beforeSend: function() { $('#wait').show(); },
        complete: function() { $('#wait').hide(); }
    });
    return false;
});
橙味迷妹 2024-08-23 20:08:27

除了 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();
 });

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.

There's the ajaxStart event

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

...and it's brother, the ajaxStop event

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

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

HTML:

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

Script:

$(document).ajaxStart(function(){
    $('#loading').show();
 }).ajaxStop(function(){
    $('#loading').hide();
 });
司马昭之心 2024-08-23 20:08:27

您可以从 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 等更复杂,但也更灵活。

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:

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:

$.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, $.get and the like, but a lot more flexible too.

司马昭之心 2024-08-23 20:08:27

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('https://i.sstatic.net/FhHRx.gif') 
            50% 50% 
            no-repeat;
opacity: 0.80;
-ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity = 80);
filter: alpha(opacity = 80)};

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

.modal {
display:    none;
position:   fixed;
z-index:    1000;
top:        0;
left:       0;
height:     100%;
width:      100%;
background: rgba( 255, 255, 255, .8 ) 
            url('https://i.sstatic.net/FhHRx.gif') 
            50% 50% 
            no-repeat;
opacity: 0.80;
-ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity = 80);
filter: alpha(opacity = 80)};
走过海棠暮 2024-08-23 20:08:27

SVG 动画可能是解决这个问题的更好方法。您无需担心编写 CSS,与 GIF 相比,您将获得更好的分辨率和 Alpha 透明度。您可以使用一些非常好的 SVG 加载动画:http://samherbert.net/svg-loaders/< /a>

您还可以通过我构建的服务直接使用这些动画: https://svgbox.net/iconset/loaders 。它允许您自定义填充并允许直接使用(盗链)。

为了完成您想要使用 jQuery 执行的操作,您可能应该隐藏一个加载信息元素,并在想要显示加载器时使用 .show() 。例如,此代码在一秒钟后显示加载程序:

setTimeout(function() {
  $("#load").show();
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

<div id="load" style="display:none">
    Please wait... 
    <img src="//s.svgbox.net/loaders.svg?fill=maroon&ic=tail-spin" 
         style="width:24px">
</div>

SVG animations are probably a better solution to this problem. You won't need to worry about writing CSS and compared to GIFs, you'll get better resolution and alpha transparency. Some very good SVG loading animations that you can use are here: http://samherbert.net/svg-loaders/

You can also use those animations directly through a service I built: https://svgbox.net/iconset/loaders. It allows you to customize the fill and direct usage (hotlinking) is permitted.

To accomplish what you want to do with jQuery, you probably should have a loading info element hidden and use .show() when you want to show the loader. For eg, this code shows the loader after one second:

setTimeout(function() {
  $("#load").show();
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

<div id="load" style="display:none">
    Please wait... 
    <img src="//s.svgbox.net/loaders.svg?fill=maroon&ic=tail-spin" 
         style="width:24px">
</div>

隐诗 2024-08-23 20:08:27

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 块添加到页面末尾关闭正文标记之前或任何您认为合适的位置即可。

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

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

For example, create the following div:

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

Set it to display: none in 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.

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

$(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 before closing your body tag or wherever you see fit.

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

筑梦 2024-08-23 20:08:27

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

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

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

This is the 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

# 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;
}
贱贱哒 2024-08-23 20:08:27

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

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.

$('#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" />

月棠 2024-08-23 20:08:27

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

Like Mark H said the blockUI is the way.

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/

安静被遗忘 2024-08-23 20:08:27

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

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

This would make the buttons disappear, then an animation of "loading" would appear in their place and finally just display a success message.

$(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>');
                    });
                }
        );
    });
});
沧笙踏歌 2024-08-23 20:08:27

我见过的大多数解决方案要么期望我们设计一个加载覆盖层,将其隐藏,然后在需要时取消隐藏,要么显示 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 文件中并将其包含在整个项目中即可。

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

调用:

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

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.

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.

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

CSS addition:

#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();
墨离汐 2024-08-23 20:08:27

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

请使用 AjaxOptions 解决这个问题:

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

Note that when using ASP.Net MVC, with using (Ajax.BeginForm(..., setting the ajaxStart will not work.

Use the AjaxOptions to overcome this issue:

(Ajax.BeginForm("ActionName", new AjaxOptions { OnBegin = "uiOfProccessingAjaxAction", OnComplete = "uiOfProccessingAjaxActionComplete" }))
半葬歌 2024-08-23 20:08:27

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

1. 在您想要旋转器的位置添加此 HTML:

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

Per https://www.w3schools.com/howto/howto_css_loader.asp, this is a 2-step process with no JS:

1.Add this HTML where you want the spinner: <div class="loader"></div>

2.Add this CSS to make the actual spinner:

.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); }
}
怀念你的温柔 2024-08-23 20:08:27

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

I use CSS3 for animation

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

别闹i 2024-08-23 20:08:27

Fontawesome 有一个加载动画图标,如果您已经在使用 font Awesome,可以直接在您的项目中使用,无需任何额外的数据负担。

<span id="loading" style="display:none"><i class="fa fa-spinner fa-pulse"></i> PLEASE WAIT </span>

然后是jquery,您可以使用以下代码来显示隐藏元素。

$(document).ajaxSend(function() {
    $('#loading').show();
});

$(document).ajaxComplete(function() {  
    $('#loading').hide();
});

$('button').click(function(){
    $('#loading').toggle();
});
<script src="https://code.jquery.com/jquery-3.6.4.slim.min.js" integrity="sha256-a2yjHM4jnF9f54xUQakjZGaqYs/V1CYvWpoqZzC2/Bw=" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<body>
<div class="m-5"> <span id="loading" style="display:none"><i class="fa fa-spinner fa-pulse"></i> PLEASE WAIT </span> </div> 
<button class="btn btn-primary"> Click me to start or stop Ajax </button>
</body>

Fontawesome has a loading animation icon which can be used directly in your project without any extra data burden if you are already using font awesome.

<span id="loading" style="display:none"><i class="fa fa-spinner fa-pulse"></i> PLEASE WAIT </span>

Then is jquery you can use following code to show hide the element.

$(document).ajaxSend(function() {
    $('#loading').show();
});

$(document).ajaxComplete(function() {  
    $('#loading').hide();
});

$('button').click(function(){
    $('#loading').toggle();
});
<script src="https://code.jquery.com/jquery-3.6.4.slim.min.js" integrity="sha256-a2yjHM4jnF9f54xUQakjZGaqYs/V1CYvWpoqZzC2/Bw=" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<body>
<div class="m-5"> <span id="loading" style="display:none"><i class="fa fa-spinner fa-pulse"></i> PLEASE WAIT </span> </div> 
<button class="btn btn-primary"> Click me to start or stop Ajax </button>
</body>

另类 2024-08-23 20:08:27

将此代码放在您的 body 标签上

<div class="loader">
<div class="loader-centered">
    <div class="object square-one"></div>
    <div class="object square-two"></div>
    <div class="object square-three"></div>
</div>
</div>
<div class="container">
<div class="jumbotron">
    <h1 id="loading-text">Loading...</h1>
</div>
</div>

并使用此 jquery 脚本

<script type="text/javascript">

jQuery(window).load(function() {
//$(".loader-centered").fadeOut();
//in production change 5000 to 400
$(".loader").delay(5000).fadeOut("slow");
$("#loading-text").addClass('text-success').html('page loaded');
});
</script>

请参阅此处的完整示例。

http://bootdey.com/snippets/view/page-loader

Place this code on your body tag

<div class="loader">
<div class="loader-centered">
    <div class="object square-one"></div>
    <div class="object square-two"></div>
    <div class="object square-three"></div>
</div>
</div>
<div class="container">
<div class="jumbotron">
    <h1 id="loading-text">Loading...</h1>
</div>
</div>

And use this jquery script

<script type="text/javascript">

jQuery(window).load(function() {
//$(".loader-centered").fadeOut();
//in production change 5000 to 400
$(".loader").delay(5000).fadeOut("slow");
$("#loading-text").addClass('text-success').html('page loaded');
});
</script>

See a full example working here.

http://bootdey.com/snippets/view/page-loader

梦萦几度 2024-08-23 20:08:27

我还发现了这样一个问题(挑战),即在数据库响应期间通知用户一些“信息”。

我的解决方案可能与这里介绍的有点不同,是好是坏?我不知道,这对我来说已经足够了。

$.ajax({ 
    type: 'ajax',
    method: 'post',
    url: '<?php echo base_url()?>skargi/osluga_skarg',
    data: { full_date: full_date, head_title: head_title },
    //async: false,             
    dataType: 'json',
    beforeSend: function() { $body.addClass("loading"); },
    success: function(data) {   
        $body.removeClass("loading");

I have also found such a problem (challenge) to inform the user about some "info" during the DB response.

My solution is probably a little different than presented here, is it good or bad? I do not know, it was enough for me.

$.ajax({ 
    type: 'ajax',
    method: 'post',
    url: '<?php echo base_url()?>skargi/osluga_skarg',
    data: { full_date: full_date, head_title: head_title },
    //async: false,             
    dataType: 'json',
    beforeSend: function() { $body.addClass("loading"); },
    success: function(data) {   
        $body.removeClass("loading");
甜尕妞 2024-08-23 20:08:27

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<button type="button" id="btn-submit" class="btn btn-info">Submit</button>

  <div class="modal fade" id="loadingModal" tabindex="-1" role="dialog" aria-labelledby="loader" aria-hidden="true" data-keyboard="false" data-backdrop="static">
    <div class="modal-dialog" style="width:50px;padding-top: 15%;">
      <div class="modal-content text-center">
        <img src="https://i.gifer.com/ZZ5H.gif" />    
      </div>
    </div>
  </div>

jQuery

$(function() {
      $('#btn-submit').click(function() {
        $('#loadingModal').modal('show');
      });
    });

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<button type="button" id="btn-submit" class="btn btn-info">Submit</button>

  <div class="modal fade" id="loadingModal" tabindex="-1" role="dialog" aria-labelledby="loader" aria-hidden="true" data-keyboard="false" data-backdrop="static">
    <div class="modal-dialog" style="width:50px;padding-top: 15%;">
      <div class="modal-content text-center">
        <img src="https://i.gifer.com/ZZ5H.gif" />    
      </div>
    </div>
  </div>

jQuery

$(function() {
      $('#btn-submit').click(function() {
        $('#loadingModal').modal('show');
      });
    });
熊抱啵儿 2024-08-23 20:08:27

这很简单。

HTML

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<body>

  <div id="cover"> <span class="glyphicon glyphicon-refresh w3-spin preloader-Icon"></span>Please Wait, Loading…</div>

  <h1>Dom Loaded</h1>
</body>

CSS

#cover {
  position: fixed;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  background: #141526;
  z-index: 9999;
  font-size: 65px;
  text-align: center;
  padding-top: 200px;
  color: #fff;
  font-family:tahoma;
}

JS - JQuery

$(window).on('load', function () {
  $("#cover").fadeOut(1750);
});

It is very simple.

HTML

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<body>

  <div id="cover"> <span class="glyphicon glyphicon-refresh w3-spin preloader-Icon"></span>Please Wait, Loading…</div>

  <h1>Dom Loaded</h1>
</body>

CSS

#cover {
  position: fixed;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  background: #141526;
  z-index: 9999;
  font-size: 65px;
  text-align: center;
  padding-top: 200px;
  color: #fff;
  font-family:tahoma;
}

JS - JQuery

$(window).on('load', function () {
  $("#cover").fadeOut(1750);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文