开发者

Chaining jQuery animations

I have come code that chains animations together (i.e. move left, then move right).

I have 20 of <li> tags laid out in a grid and I am animating the main <ul> to move the required <li> into view.

Code:

x and y are co-ordinates,

howFast is set to 1200,

easeItIn is set to "easeOutBounce"

if ($(window).width()<1259) { 
  if (screenFlipMode == "chained") {
    (function(x, y) { //Small Chained
      $('.elements').animate({
        top: y+'px'
      }, howFast, easeItIn,function() {
        $('.elements').animate({
          left: x+'px'
        }, howFast, easeItIn);
      });
   })(x,y); 
}

Now, the problem I have is that if I want to move from the first <li> to the second <li> then it still tries to move the Y-Axis (which means I have to wait 1200m/s until the X-Axis animation comes into play).

So... Lovely people... My question is, how can I write an if clause that would say "if target <li> is on the same row, then don't do the Y-Axis a开发者_高级运维nimation...?

[EDIT] My grid is set up as follows, I want to disable the Y-Axis or X-Axis dependant on whether the next destination is on the same row. (IMAGE BELOW).

alt text http://demo.squeezedigital.com/barrie-test/jquery-grid.gif

>.<


Animations are queued by default, so there's no point in applying the second animation within the first animation's callback.

By using filter() you can filter out all of the elements that are not on the same row and then only apply the y animation to them, then you can apply the x animation to the entire collection.

$('.elements')
    .filter(function(){
        return $(this).offset().top !== y;
    })
    .animate({
        top: y
    }, howFast, easeItIn)
    .end().animate({
        left: x
    }, howFast, easeItIn);


You maybe can solve that problem without an if statement. Just adapting your selector might help.

$('.elements:first-child')

for instance. Another could be

$('table').find('tr').find('.elements:nth-child(2)')

jQuery selectors


The key here is that you can animate multiple properties at the same time. So, remove your callback function, and simply add another property to the params of the first animation:

if ($(window).width()<1259) 
{ 
    if (screenFlipMode == "chained") 
    {
        function(x, y)
        { //Small Chained
            $('.elements').animate({
                top: y,
                left: x
            }, howFast, easeItIn)
        }(x,y); 
    }
}

If either property is already at that value, it won't need to change, and thus that property won't animate. The other one will still animate, though.

Also, jQuery automatically treats numeric values as pixes when using animate(), so there's no need to append "px". That may actually be hurting your performance.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜