jQuery使div重复淡入淡出

10

您好,我有一系列通过for循环创建的div,如下:

var myDiv ='#bannerHolder'
        var fib_str = '1, 2, 3, 5, 8, 13, 21, 1, 2, 3, 5, 8, 13, 21, 1, 2, 3, 5, 8, 13, 21, 1, 2, 3, 5, 8, 13'
        var widths_str = '33px, 31px, 35px, 9px, 16px, 50px, 33px, 24px, 40px, 20px, 63px, 30px, 10px, 29px, 11px, 12px, 51px, 31px, 35px, 11px, 14px, 50px, 30px, 25px, 38px, 20px, 35px'
        var pos_str = '0px, 44px, 105px, 144px, 153px, 203px, 236px, 269px, 280px, 354px, 374px, 437px, 447px, 457px, 506px, 517px, 529px, 604px, 646px, 687px, 698px, 712px, 762px, 787px, 823px, 895px, 915px'
        var color_str = '#D5E1D7, #18D4C9,#BF51C3,#1E82C9, #EDEDED, #E1C981, #C9A94F, #BDBCAA, #5DB522, #EB2F34, #823133, #004BD8, #A6A0A0, #DS9F36, #FFDB00, #69944F, #18D4C9, #BF51C3, #1E82C9, #6B949A, #FFDB00, #819E64, #BDBCAA, #54BA43, #EB2F34, #823133'
        var width = widths_str.split(",");
        var pos = pos_str.split(",");
        var color = color_str.split(",");
        var fib = fib_str.split(",");
        console.log(width);
        console.log(pos);
        console.log(color);
        var counter = width.length
        var stopper = false;
for(i=0;i<counter;i++){
                var html = '<div id ="stripe'+i+'"/>'   
                $(myDiv).append(html)
                $('#stripe'+i).css({  'top': 0,  'left': pos[i],'position': 'absolute', 'float': 'left', 'background-color' : color[i]})
                $('#stripe'+i).attr({ 'min-width' : width[i], 'min-height' : '100px'  })
                $('#stripe'+i).width(width[i])
                $('#stripe'+i).height('100px')


            };

我想要的是每个创建的div都能完全淡出,然后再淡入,并且这个过程可以无限循环。如果我尝试使用.animate()并调用Complete:属性的函数,我会得到太多递归而且页面会崩溃,我该怎么做呢?


2
<blink><div>....</div></blink> - Nick Craver
你明白我的例子吗 Bryan?如果进行适当的调整,它将适用于你的代码。 - Orbling
1个回答

18
问题在于从一个fade*()例程中递归调用另一个,需要将序列设置为可重复以非递归方式调用。
以下是一种相当简洁的方法:
演示在此处:http://jsfiddle.net/ZZGhn/
$('.block').bind('fade-cycle', function() {
    $(this).fadeOut('fast', function() {
        $(this).fadeIn('fast', function() {
            $(this).trigger('fade-cycle');
        });
    });
});

// This next block of code just sets all the triggers off at random times
// The point is to start them using .trigger('fade-cycle');
// All can be started simultaneously with $('.block').trigger('fade-cycle');

$('.block').each(function(index, elem) {
    setTimeout(function() {
        $(elem).trigger('fade-cycle');
    }, index * 250);
});

1
没事了,我添加了一个条件来检查变量是否为真,在触发每个重复之前。 - trusktr
1
+1 对于使用事件触发器的有趣解决方案表示赞赏,虽然今天可以使用CSS3动画来实现,但我喜欢这种思路 :) - Benjamin Gruenbaum
1
我知道这是一个老问题,但是在停止它方面,您还可以从.block中解除事件触发器,这将打破循环。 - Rick Burgess
@RickBurgess:非常正确,明智的方法 - 这将在循环的淡入部分之后完成。 - Orbling
使用 fadeTo("fast",0.01) 而不是 fadeOut() 可以避免 divs 完全被移除的问题。请参考 http://api.jquery.com/fadeto/。 - Adriano

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接