8

我正在尝试使每个语句中的 div 淡入/淡出。问题是在淡入/淡出完成之前调用下一个项目。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>

<div id='one'>one</div>
<div id='two'>two</div>
<div id='three'>three</div>

<script>
$.each([ "one", "two", "three"], function() {
  console.log( 'start - ' + this );
  animate( this );
  console.log( 'end - ' + this );
});

function animate( id )
{
  box = '#' + id;

  $(box).fadeOut( 500, function( )
  {

    console.log('showing - ' + id);
    $(box).fadeIn( 500 );
    $(box).css('backgroundColor','white');

  });

}
</script>

控制台显示 -

start - one
end - one
start - two
end - two
start - three
end - three
showing - one
showing - two
showing - three

我想要类似的东西 -

start - one
showing - one
end - one
start - two
showing - two
end - two
start - three
showing - three
end - three

那么在继续下一个值之前,我如何才能等待每个“每个”都完全完成呢?

4

3 回答 3

7

您将不得不使用回调 - 当前函数完成时执行的函数。要做到这一点,.fadeOut你会这样做:

$('#element').fadeOut( 400, myFunction );

在 fadeOut 完成之前,不会调用 myFunction。使用 $.get 的 AJAX 调用也可以有回调函数。

这是一个有效的示例,尽管我确信有更好的方法:

function animate(myArray, start_index) {

    // Stealing this line from Sam, who posted below.
    if(!start_index) start_index = 0;

    next_index = start_index+1;
    if(next_index > myArray.length) { return; }

    box = '#' + myArray[start_index]; 
    $(box).fadeOut(500, function() { animate(myArray,next_index); });
}

然后在你的 document.ready 你会打电话:

animate(theArray);
于 2010-01-30T16:20:40.430 回答
1

听起来您正试图“循环”通过 div 列表。你检查过jQuery Cycle 插件吗?

于 2010-01-30T16:10:48.597 回答
1

怎么样,通过遍历函数内数组中的每个项目来制作动画?

var elements = [ "one", "two", "three"];
animate(elements);

function animate( elements, index )
{
    if(!index) index = 0;
    var box = '#' + elements[index];
    var $$box = $("#box");
    console.log( 'start - ' + elements[index] );
    $$box.fadeOut( 500, function( )
    {
        console.log('showing - ' + elements[index]);
        $$box.fadeIn( 500, function() {
            console.log( 'end - ' + elements[index] );
            if(elements[++index]) animate(elements, index);
        } ).css('backgroundColor','white');
    });
}

如果需要,您甚至可以循环回到起点:

var elements = [ "one", "two", "three"];
animate(elements);

function animate( elements, index )
{
    if(!index) index = 0;
    var box = '#' + elements[index];
    var $$box = $(box);
    console.log( 'start - ' + elements[index] );
    $$box.fadeOut( 500, function( )
    {
        console.log('showing - ' + elements[index]);
        $$box.fadeIn( 500, function() {
            $$box.css('backgroundColor','white');
            console.log( 'end - ' + elements[index] );
            // go to next element, or first element if at end
            index = ++index % (elements.length);
            animate(elements, index);
        } );
    }).css('backgroundColor', 'aqua');
}
于 2010-01-30T16:41:25.360 回答