jQuery 优化循环动画函数

3

我希望能找到一种更有效的方法来实现这个结果:

http://jsfiddle.net/H4sjf/1/

使用setInterval().each()以及随后的.animate()使得这个脚本变得相当缓慢。有没有一种利用其他“成本较低”的过程/函数来实现这个结果的方法?

2个回答

1

你可以为animate()创建一个回调函数,重新对“this”进行动画处理,并将自身作为回调函数调用,而不是使用setinterval。

[编辑] 我删除了一些不必要的代码:

http://jsfiddle.net/8kgAB/1/

DoPopulateSoundBoard();
function DoPopulateSoundBoard(){
    $('.sound-syn-column').each(function(){
        var dSoundSyn = '';
        for( i = 0; i <= 8; i++ ){
                dSoundSyn += "<div class='ui-corner-all sound-syn'></div>";
            }
        $(this).append( dSoundSyn + "<div class='sound-syn-cover'></div>" );
    });




        $('.sound-syn-cover').each(function(){
                    test34($(this));
        });

}

function test34(obj){
    obj.animate({height: Math.floor( Math.random()*56) }, 500, function(){
            test34($(obj));
    });       
}

不确定这是否更快,但可能会更快,因为setinterval非常慢。


请研究一下 $(..)each(function(){ console.log(this) }) 中的 this 所代表的内容。 - tereško
如果我没记错的话,在 $(...)each(function(){ //this }) 中的 this 指的是当前正在被 each 处理的对象...这就解释了为什么我的代码能正常运行。你想要说什么?你能跟我解释一下我做错了什么吗? - BumbleShrimp
@tereško 在 each() 回调函数内运行了 console.log($(this)),并记录了正在进行动画的元素,这正是我们想要传递到函数中的内容。你能解释一下我做错了什么,以便我更新答案吗? - BumbleShrimp

0
你可以通过将单独的 setInterval() 函数添加到每个 div 中来分离 setInterval() 和 .each():
$('.sound-syn-cover').each(function(){
    var $this = $(this);
    $this.data('intervalCallback', setInterval(function(){
        $this.animate({height: Math.floor( Math.random()*56) }, 500);
    }, 300));
});

jsFiddle


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