1
function character_1() {
    $("#character_1").animate({"top": "0"}, 3000, function() {
        $(this).fadeOut(2000);
        character_2();
    });
};

function character_2() {
    $("#character_2").animate({"top": "0"},3000, function() {
        $(this).fadeOut(2000);
        character_3();
    });
};

function character_3() {
    $("#character_3").animate({"top": "0"},3000, function() {
        $(this).fadeOut(2000);
        character_1();
    });
};

$(document).ready(function() {
    character_1();
});

上記のコード。character_1(); には戻りません。それらをループとして実行したいと思います。誰でも助けてください。

4

2 に答える 2

4

戻ってきますが、何の関係もなく、すでにアニメーション化されフェードアウトしています。

その関数にアラートを入れて、自分で確認してください。

function character_1() {
    alert("I'm back!!!"); // <<=====================
    $("#character_1").animate({"top": "0"}, 3000, function() {
        $(this).fadeOut(2000);
        character_2();
    });
};

ライブデモ

要素を切り替えたい場合は、次を使用しますtoggle

$(this).toggle(2000); // instead of "fadeOut(2000)";

this呼び出し間で保持するようにしてください。

于 2012-05-30T21:14:36.193 に答える
2

As I mentioned in comments: Your looping is fine, but all elements are faded out after executing character_3() and so you don't see the return back to character_1(). You need to reset the animation to original state before you could call character_1(). Check below for an sample of how to set it back to original state.

Also the sequencing was little off because of the fadeOut animation, so I moved to call to next animation inside fadeOut callback so that it is properly sequenced.

Edit: I have done some optimization and used timer instead of endless loop. Check below,

Can handle any number of boxes with no change to the code

$(function() {
    var $chars = $('.chars');
    var curIndex = 0, charTop = 0;

    function animateChars() {
        setTimeout(function() {
            if (curIndex >= $chars.length) {
                curIndex = 0;
                if (charTop == 200) {
                    charTop = 0;
                } else {
                    charTop = 200;                    
                }
                $.when($chars.fadeIn(2000)).then(animateChars());
            } else {
                console.log(curIndex);
                $chars.eq(curIndex).animate({
                    "top": charTop
                }, 3000, function() {
                    $(this).fadeOut(2000, function() {
                        curIndex++;
                        animateChars();
                    });
                });
            }

        }, 100);
    }
    animateChars();
});

DEMO

于 2012-05-30T21:29:51.677 に答える