Spinning wheel in jQuery

2019-05-28 11:50发布

I am using following code to show a spinning wheel:

$("#loading")
.hide()
.ajaxStart(function(){

    $(this).show();
    setTimeout("3000");
})
.ajaxStop(function(){

    $(this).hide("slow");
})
;   

and:

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

Problem: "setTimeout() is not working. And how can I display the image at the centre of webpage?"

4条回答
家丑人穷心不美
2楼-- · 2019-05-28 12:24

I dont understand why you're using the timer, you can simply turn it on at start of ajax request, and then on success or error turn it off, like:

$('#loading').show();

$.post(url, request)

    .success(function(data) {
        $('#loading').hide();
        // Do what you want with data
    })

    .error(function(data) {
        $('#loading').hide();
        // Show error message
    });

To have your loading image in the middle of the page, make sure that it's container is within a 100% height parent, and if it is nested, make sure none of its parents are position:relative.

#loading {
    position:relative;
    width:100%;
    height:100%;
}

#loading img {
    margin-top: -12px; // Half images height;
    margin-left: -12px; // Half images width;
    position:absolute;
    top:50%;
    left:50%;
}

OR

#loading {
    width:100%;
    height:100%;
}

#loading img {
    width:24px // Images width
    height:auto; // If Image size changes don't mess with proportions
    margin:0 auto;
    margin-top:48%;
}
查看更多
迷人小祖宗
3楼-- · 2019-05-28 12:33

You use the SetTimeout function in a wrong way


setTimeout(function(){ 

// do sth

 }, 3000);

查看更多
We Are One
4楼-- · 2019-05-28 12:45
#loading {
   display: none;
   position: fixed;
   top: 48%;
   left: 48%
}

JS

$('#loading').ajaxStart(function(){
   var that = $(this)
    setTimeout(function() {
       that.show();
    }, "3000");
}).ajaxStop(function(){
    $(this).hide("slow");
})
查看更多
Animai°情兽
5楼-- · 2019-05-28 12:48

setTimeout takes 2 paramter, the first one is the callbackfunction and the second is the timeout in msec eg.

setTimeout(funcname,1000);

or

setTimeout(function(){
    //do stuff
},1000);

to display your image in center of the webpage you can use eg. this technique

#loading {
    position:absolute;
    top:50%;
    left:50%;
    width:100px;
    margin-left:-50px; //negative half of width
    height:80px;
    margin-top:-40px; //negative half of height
}
查看更多
登录 后发表回答