开发者

JS/jQuery delay loop to get desire result (delay() not working)

I'm trying to create an loading icon by moving the css 'background-position' of an image in a loop:

$('#LoginButton').click(function () {

    var i = 1, h = 0, top;

    for (i开发者_如何学JAVA = 0; i <= 12; i++) {
        h = i * 40;
        top = h + 'px';
        $('#ajaxLoading').css('background-position', '0 -' + top).delay(800);
    }

});

The problem here is that it runs to fast so I don't se the 'animation' of the moving background. So I added jquerys delay(), but:

delay(800) is not working because delay() only works in jquery animation effects and .css() is not one of those.

How to delay this loop?


I'd suggest using jQuery timer plugin: http://jquery.offput.ca/js/jquery.timers.js

$('#LoginButton').click(function () {
    var times = 13;
    var delay = 300;
    var h = 0, top;
    $(document).everyTime(delay, function(i) {
        top = h + 'px';
        $('#ajaxLoading').css('background-position', '0 -' + top);
        h += 40;
    }, times);
});

In case you don't want any plugins, use setInterva/clearInterval:

$('#LoginButton').click(function () {
    var delay = 300;
    var times = 13;
    var i = 0, h = 0, top;

    doMove = function() {
        top = h + 'px';
        $('#ajaxLoading').css('background-position', '0 -' + top);
        h += 40;

        ++i;
        if( i >= times ) {
            clearInterval( interval ) ;
        }
    }

    var interval = setInterval ( "doMove()", delay );
});


Have you looked at using animate() instead of css()? I'm not 100% sure I understand what you're trying to accomplish, so this is kinda a shot in the dark.

http://api.jquery.com/animate/


Chrome, Safari and IE3+ should support background-position-y, so if you're targeting these specific browser, using jquery you could just make a timed animation() on backgroundPositionY property - http://snook.ca/archives/html_and_css/background-position-x-y (On Firefox the effect won't work)


You can use setTimeout() and clearTimeout() functions in order to accomplish that.

IE:

var GLOBAL_i = 0;

function doAnimation() {

    var h = GLOBAL_i * 40;
    var top = h + 'px';
    $('#ajaxLoading').css('background-position', '0 -' + top);

    if (GLOBAL_i < 12) {
        GLOBAL_i++;

        t=setTimeout(doAnimation, 800);
    }
}

$('#LoginButton').click(function () {

    doAnimation()

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜