$ .fn setInterval用于具有不同计数值的多个元素

时间:2013-02-22 19:40:01

标签: javascript jquery animation setinterval infinite

我可以设法在不同速度的多个元素上进行无限动画,但我使用了几个setInterval函数。我的目标是使用一个函数执行此操作,当我使用$.fn尝试此操作时,它们都以相同的速度进行动画处理。我哪里做错了?

Here is not accurate jsFiddlehere is targeted sample

jQuery的:

var eleHeight = $('.drop_leds').height();
var windowH = $(window).height();
var count = 0;
var counter;
var limit = windowH + eleHeight;

$.fn.goDown = function(x) {
    var _this = this;
    return counter = window.setInterval(function() {
        if( count >= 0 && count < limit ) {
            count += x;
            _this.css({'top':count +'px'});
        }
        else if( count >= limit ) { 
            count=0; _this.css({'top':'-'+ eleHeight +'px'});
        }

    },1);
};

$('#l_0,#l_6').goDown(1);
$('#l_1,#l_4').goDown(3);
$('#l_2,#l_7').goDown(4);
$('#l_3,#l_5').goDown(2);

HTML / CSS:

<div id="l_0" class="drop_leds"></div>
<div id="l_1" class="drop_leds"></div>
<div id="l_2" class="drop_leds"></div>
<div id="l_3" class="drop_leds"></div>
<div id="l_4" class="drop_leds"></div>
<div id="l_5" class="drop_leds"></div>
<div id="l_6" class="drop_leds"></div>
<div id="l_7" class="drop_leds"></div>

.drop_leds {position:absolute; width:10px; height:60px; background:black; top:0;}
#l_0 { left:40px; }#l_1 { left:70px; }#l_2 { left:110px; }#l_3 { left:140px; }
#l_4 { left:180px; }#l_5 { left:210px; }#l_6 { left:220px; }#l_7 { left:240px; }

Source.

1 个答案:

答案 0 :(得分:3)

每次调用count时,您都会覆盖$.fn.goDown,因此所有计时器都会使用相同的count值。将其移至插件内部范围内以解决问题:

$.fn.goDown = function(x) {
    var count = 0;
    var counter;
    var _this = this;
    return counter = window.setInterval(function() {
        if( count >= 0 && count < limit ) {
            count += x;
            _this.css({'top':count +'px'});
        }
        else if( count >= limit ) { 
            count=0; _this.css({'top':'-'+ eleHeight +'px'});
        }

    },1);
};

Fiddle

这样,每个间隔counter将只有在创建间隔的执行上下文中可访问的相应count变量。正如你如何确定插件范围内_this的范围。