开发者

Alert Box Running First?

I have some jQuery/JS below. The first thing to run is the alert box at the end.

$(document).ready(function() {
    $("#id1 img , .msg").stop().animate(
        { width: '300px', height: '300px'}, 
        { duration: 'slow', easing: 'easeInSine' }).pause(3000);

    $(".msg").animate(
        { width: '50px', height: '50px' }, 
        { duration: 498, easing: 'easeOutSine' });
    $("#id1 img").animate(
        { width: '50px', height: '50px' }, 
        { duration: 500, easing: 'easeOutSine' });

    $("#id1 img , .msg").animate(
        { width: '300px',height: '300px'}, 
        { duration: 'slow', easing: 'easeInSine' }).pause(3000);

    alert('eh?');
});

I do have a easing plugin.

If I run this the alert will show, and then the first animate will happen in the background but not be shown. It will just appear at the final size.

Shouldn't the alert run at the end of all the animation?

开发者_运维问答Can anyone explain why this is happening?


As other commenters have mentioned, the animate method is non-blocking and thus this is the correct behavior. If you want the alert to be called at the end of an animation, take a look at the animate method's callback parameter. The documentation states: "A function to be executed whenever the animation completes, executes once for each element animated against."

http://docs.jquery.com/Effects/animate


This pause plugin says that it "holds everything in the queue" for the specified amount of time. It will not actually pause execution (there is no sleep in javascript).

So, this is exactly the expected thing, that the alert will show up first.


jQuery animate does not block execution when animating. Instead, it is only queued when you call the statement $().animate is called.

Thus your alert() statement was "called first". But in fact, the animate statements was called before alert(), only that alert() has blocked execution before the animation is complete.


Just as in the beginning of the code where you have the

$(document).ready(function(){

That function states that after the document is ready, load the function that follows. So at the end of the animation that you have running, you'll want to add another function telling it to run the alert after the animation completes. Here's an example:

 $(document).ready(function(){
   $("button").click(function(){
     $("p").animate({width:25},3000,function(){
      alert("The paragraph has been animated");
    });
   });
  });

When the button is clicked, all p elements have their width shrunken to 25pixels over a period of 3seconds (jQuery reads in millisecons) and once that completes, it runs the function of the alert "The paragraph has been animated". Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜