jQuery change value after animation is done

眉间皱痕 提交于 2020-01-14 04:18:28

问题


This code down never call alert 'ane is true'.

It is possible to change local variable 'ane' from jQuery method "animate"?

In my code variable 'ane' is always false. I try this method for change of 'ane' value:

function anim() {
  var ane = false;
  $('#element').animate({left:'100px'}, 5000, function(){ ane = true; });
  while(!ane){}
  alert('ane is true');
}

This also does not work for me:

function anim() {
  var ane = false;
  var ant = function(){ ane = true; }
  $('#element').animate({left:'100px'}, 5000, ant);
  while(!ane){}
  alert('ane is true');
}

Thanks for reply.


回答1:


Live Demo

function anim() {
  var ane = false;
    $('#element').animate({left:'100px'}, 5000, function(){
        ane = true;
        if(!$(this).is('animated')){
            alert(ane);
        }
    });
}

Once the animation completes you will be alerted.




回答2:


JavaScript has only a single thread. If you use

while(!ane){}

jQuery can't run, thus not execute the animation, thus not complete the animation and set ane to true.




回答3:


Try this:

function anim() {
  var ane = false;
  var ant = function(){ ane = true; }
  $('#element').animate({left:'100px'}, 5000, ant);
  setInterval(function(){ if(ane) { alert('ane is true'); } }, 100); 
}

ane should eventually be true, because this time the execution is not locked by the while loop.




回答4:


Thanks to all. I used this to continue in the same executed function after animation:

// animation part
var ane = false; // check if animation end
$('#element').animate({left:'100px'}, 5000, function(){ane = true;});

// continue only if animation done
var fcb = setInterval(function(){ if(ane) {
  // continue executing function
  clearInterval(fcb); 
  // ...
  // nextCodePart();
  // ...
} }, 20);



回答5:


The answer of @Loktar is correct, but you could omit the condition

function anim() {
  var ane = false;
    $('#element').animate({left:'100px'}, 5000, function(){
        ane = true;
        // the animation is already finished
        // if(!$(this).is('animated')){
        //    alert(ane);
        //}
        alert(ane);

    });
}

because the function is called when the animation is actually finished.

Using the latest version of jQuery (>= 1.8) you can check if the animation is actually completed using the option done:

function anim() {
    var ane = false;
    $('#element').animate({width:'100px'}, 
                      {duration: 5000,
                       done: function () {alert("done")}
                      });
}


来源:https://stackoverflow.com/questions/5302017/jquery-change-value-after-animation-is-done

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