动画完成后jQuery更改值

时间:2011-03-14 17:18:10

标签: javascript jquery variables jquery-animate

这段代码从不调用警告'是真的'

可以从jQuery方法“animate”更改局部变量'ane'吗?

在我的代码变量'ane'总是假的。我尝试这种方法来改变'ane'值:

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

这对我也不起作用:

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

感谢您的回复。

5 个答案:

答案 0 :(得分:4)

Live Demo

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

动画完成后,您将收到提醒。

答案 1 :(得分:0)

JavaScript只有一个线程。如果你使用

while(!ane){}

jQuery无法运行,因此无法执行动画,因此无法完成动画并将ane设置为true。

答案 2 :(得分:0)

试试这个:

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最终应该是真的,因为这次执行没有被while循环锁定。

答案 3 :(得分:0)

感谢所有人。我在动画后使用它继续执行相同的执行函数:

// 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);

答案 4 :(得分:0)

@Loktar的答案是正确的,但你可以省略条件

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);

    });
}

因为在动画实际完成时会调用该函数。

使用最新版本的jQuery(> = 1.8),您可以使用完成选项检查动画是否实际完成:

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