admin管理员组

文章数量:1430700

I have an event listener that calls two animation actions. Unfortunately their starts are staggered by a small amount (e.g. the first in the function starts first).

Does anyone know a way to properly sync them up?

Here's my code:

$("#nav ul li a").hover(
    function(){
        $(lastBlock).children("div").animate({width: "0px"}, { queue:false, duration:400, easing:"swing" });
        $(this).children("div").animate({width: maxWidth+"px"}, { queue:false, duration:400, easing:"swing"});
        lastBlock = this;
    }
);

Because the first animation runs slightly before the second, it causes the overall width to bee momentarily unequal, which looks a bit funky.

I have an event listener that calls two animation actions. Unfortunately their starts are staggered by a small amount (e.g. the first in the function starts first).

Does anyone know a way to properly sync them up?

Here's my code:

$("#nav ul li a").hover(
    function(){
        $(lastBlock).children("div").animate({width: "0px"}, { queue:false, duration:400, easing:"swing" });
        $(this).children("div").animate({width: maxWidth+"px"}, { queue:false, duration:400, easing:"swing"});
        lastBlock = this;
    }
);

Because the first animation runs slightly before the second, it causes the overall width to bee momentarily unequal, which looks a bit funky.

Share Improve this question asked Mar 26, 2009 at 20:45 Tom WrightTom Wright 11.5k15 gold badges79 silver badges152 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

There was a recent disussion about this exact topic on the jQuery dev list. They created a few test cases you might wanna look at. Specially the Johns test.

Here's the discussion topic btw.

The trick is to have a single interval/callback in which all elements are updated. You can find an example in my post here:

Can I implement a callback with each animation step in jQuery?

What you end up is basically:

var el1 = $("#element1");
var el2 = $("#element2");

var animation = new AnimationTimeline( {
    easing: "swing"
  , onstep: function( stepValue, animprops )
    {
      // This is called for every animation frame. Set the elements:
      el1.css( { left: ..., top: ... } );
      el2.css( { left: ..., top: ... } );
    }
  });

// And start it.
animation.start();

本文标签: javascriptIs there any way to make two jQuery animations run (properly) simultaneouslyStack Overflow