How can I create a “Please Wait, Loading…” animation using jQuery?

后端 未结 17 2012
长情又很酷
长情又很酷 2020-11-22 00:07

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

17条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 00:42

    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 = '
    ' + ''+ '
    '; 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();
    

提交回复
热议问题