How to start one jQuery animation only after another is totally complete

亡梦爱人 提交于 2019-12-11 02:11:11

问题


I have a couple situations where I need to animate an element, say either moving it to the left, or fading it in, but only after an initial animation is 100% complete.

So like, say I have a search drawer that slides out from the top of the page when you click a search icon. Thats easy right:

$('.search-toggle').on('click', function(){
   $('.search-drawer').slideToggle(); // or fadeIn(), show() ect..
});

But what if like, I click on a search toggle at the BOTTOM of a page, and I need my page to scroll up to the top BEFORE displaying the search drawer? I tried something like this:

$('.search-toggle').on('click', function(){
   $('html, body').animate({ scrollTop: 0 }, "slow").find('.search-drawer').slideToggle(); // or fadeIn(), show() ect..
});

but the two animations run at the same time. I've tried using delay but that doesn't seem to work and would likely cause a noticeable delay when the top link is click as opposed to the bottom.

That said, I'm also trying to run an animation where when you click on an element, I want it to move to the left by like 330px and then, AFTER it's reached that position, another element would slide in Or I would have the second element slide in first and THEN the first element would do something. The point is, how do I get the animated to finished before beginning another one.

So for my second example, I see that the animate callback doesnt really work. I have this for another animation:

 $first.animate( {
     left : "-=660"
    }, 
    300, 
    function(){
      $second.animate({ left: '-='+startPosition });
    }
 }

So in this example, in theory first $first would move left 660 pixels and THEN $second would move left X amount right? It doesnt, they look like the move at the same time. Or rather, $second starts animating before $first.


回答1:


You need to change your function so it will wait for the first animation to complete:

$('.search-toggle').on('click', function(){
    $("body").animate({ scrollTop: 0 }, "slow", function(){
        $('.search-drawer').slideToggle(); // or fadeIn(), show() ect..
    });
});


来源:https://stackoverflow.com/questions/18132982/how-to-start-one-jquery-animation-only-after-another-is-totally-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!