【问题标题】:$.fn setInverval on multiple elements with different couting values$.fn setInterval 在具有不同计数值的多个元素上
【发布时间】:2013-02-08 12:44:15
【问题描述】:

我可以设法以不同的速度对多个元素进行无限动画,但我使用了几个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.

【问题讨论】:

  • aaah.. 让它停下来.. 当它在旁边运行时,我无法专注于你的代码......(开玩笑)

标签: javascript jquery animation setinterval infinite


【解决方案1】:

每次调用$.fn.goDown 时都会覆盖count,因此所有计时器最终都使用相同的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 的方式完全相同。

【讨论】:

  • 谢谢伙计,看来我犯了一个简单的错误(:
猜你喜欢
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
相关资源
最近更新 更多