我可以设法在不同速度的多个元素上进行无限动画,但我使用了几个setInterval
函数。我的目标是使用一个函数执行此操作,当我使用$.fn
尝试此操作时,它们都以相同的速度进行动画处理。我哪里做错了?
Here is not accurate jsFiddle和here 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; }
答案 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);
};
这样,每个间隔counter
将只有在创建间隔的执行上下文中可访问的相应count
变量。正如你如何确定插件范围内_this
的范围。