上面的代码。 它不返回到character_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(); });The code above. It doesn't return to character_1(); I'd like to have them running as loop. Anyone help please?
最满意答案
正如我在评论中提到的那样:您的循环很好,但执行character_3()后所有元素都会淡出,因此您不会看到返回到character_1() 。 在调用character_1()之前,您需要将动画重置为原始状态。 请在下面检查如何将其设置回原始状态的示例。
由于fadeOut动画也排序很少,因此我调用fadeOut回调中的下一个动画,以便正确排序。
编辑:我做了一些优化,并使用计时器,而不是无限循环。 检查下面,
无需更改代码即可处理任意数量的框
$(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
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
更多推荐
发布评论