我有2个元素与类wave-bar.(实际上更多,但为了这个例子,让我们说2)
下面的代码将元素的高度更改为随机值(以创建波形(想想音频播放器)效果).
代码当前为第一个元素更改高度10000次,当它完成时,它继续并更改第二个元素的高度.
但是我希望这两个元素同时获得随机高度.这样第二个元素的动画就不会等待第一个元素完成.
$('.wave-bar').each(function() {
var bar = $(this);
for (var i=0;i<=10000;i++) {
window.setTimeout(function() {
var rand_no = Math.floor(Math.random()*19);
bar.height(rand_no);
bar.css('margin-top', (18-rand_no)+'px');
}, 500);
}
});
Run Code Online (Sandbox Code Playgroud)
如何设置?
我将创建一个简单的jQuery插件并将其应用于每个元素,如下所示:
$.fn.pulseRandom = function () {
var repulse = function ( $elem ) {
var rand = Math.floor( Math.random() * 100 ),
time = Math.floor( Math.random() * 250 ) + 250;
$elem.animate({ height: rand, 'margin-top': 100 - rand }, time - 1);
setTimeout(function(){ repulse( $elem ); }, time);
};
repulse( this );
};
$('.wave-bar').each(function(i,ele){
$(ele).pulseRandom();
});
Run Code Online (Sandbox Code Playgroud)
我还将时间随机化了一点,使它看起来更有机.