0

I have two Divs

<div id="squareone"></div>
<div id="squaretwo"></div>

And when the page loads I want each div too ->$('#squareone').animate({top: '1px'},1000); The question is - Is it possible to toggle between these two divs automatically when the page loads maybe with a timer or by using the setInterval function?

So when the page loads $('#squareone').animate({top: '1px'},1000);

and then 2 secs later $('#squaretwo').animate({top: '1px'},1000);

and then repeatedly for 20 sec?

Thanks!

4

1 回答 1

0

Try doing an infinite recursive loop:

function toggleDivs($this){
    var $that = ($this.attr('id') === 'squareone' ? $('#squaretwo') : $('#squareone'));

    $this.animate({top:1},1000,function(){
        toggleDivs($that);
    });
}

Then on page load just call it:

$(function(){
    toggleDivs($('#squareone'));
});

If you want to stop it after 20 seconds:

function toggleDivs($this,count){
    var $that = ($this.attr('id') === 'squareone' ? $('#squaretwo') : $('#squareone'));

    $this.animate({top:1},1000,function(){
        if(count <= 20){
            count++;
            toggleDivs($that,count);
        }
    });
}

And just include the starting number in the call:

$(function(){
    toggleDivs($('#squareone'),1);
});

This is because you are animating for 1 second, obviously the number of cycles would change if you wanted to do it faster or slower (count <= 40 if you did animation for 500 instead of 1000, for example).

于 2013-06-04T15:33:41.127 回答