开发者

Binding animation on many elements

I try to do some kind of grid that need to show dot based animation in the future. But it seams to perform pretty slowly even with a few elements (i need to开发者_C百科 apply it to maybe 5times that many items)

$('div').bind('shrink', function(){
       var $that = $(this).find('> em > span');
       $that.animate({'width': '3px', 'height': '3px'}, 500);
    }).bind('grow', function(){
       var $that = $(this).find('> em > span');
       $that.delay(50).animate({'width': '100%', 'height': '100%'}, 300);
    }).append('<em><span><span><em/>');
//triggering shrink and grow on hover

before starting to do complex animations i wanted to test it with a hover effect.

you can take a look at the demo here: http://jsfiddle.net/meo/GvfVb/7/

How could i improve the performance of this script?


I seem to get some performance improvements with this version:

Example: http://jsfiddle.net/patrick_dw/GvfVb/10/

var shrink = function() {
    $(this).animate({
        'width': '3px',
        'height': '3px'
    }, 500);
};
var grow = function() {
    $(this.firstChild.firstChild)
        .delay(50).animate({
        'width': '20px',
        'height': '20px'
    }, 300);
};

$('div').append('<em><span><span><em/>')
    .find('> em > span').mouseenter( shrink )
    .end().mouseleave(grow)
    .click(function() {
        $(this).unbind('mouseleave', grow);
});

Here are the changes I made:

  • Changed shrink and grow into named functions, so that .trigger() doesn't need to be called to fire them, while retaining the ability to remove them by name.
  • Placed the mouseenter event directly on the <span> tag so you don't need to do a .find() every time mouseenter fires.
  • The mouseleave needs to be on the <div> so I optimized it by removing the .find() and replacing it with a native this.firstChild.firstChild.
  • This was probably the biggest performance improvement: I changed the grow function to animate the width to an absolute value of 20px instead of 100%. Things really smoothed out with that change.

You could also probably unbind the mouseleave when you click so that it isn't firing to no effect after the mouseenter has been unbound.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜