2012-06-20 126 views
0

我有一个盒子,当我点击它,我想盒子动画第一,然后将其返回到原来的位置,代码:jQuery的动画处理队列功能只执行一次

$('#test').click(function() { //#test is the box 
     var o ={  //remember the original position 
      "x":"0px", 
      "y":"0px"   
     } 

     $(this).animate({ 
      "left": "15px", 
      "top": "15px"   
     }).queue(function() { //afte execute the animate, return to its origin position 
      $(this).css({ 
       'left': o.x, 
       'top': o.y 
      })    
     }) 
    }) 

,但问题是,这个效果只能执行一次,当我第二次点击它,它永远不会执行,那么为什么会发生这种情况?我该如何解决这个问题?

这里是唯一example

回答

1

KiroSora09的答案可能是简单的,但使用排队功能的正确方法是这样执行它之后,从队列中删除的功能:

$('#test').click(function() { //#test is the box 
    var o ={  //remember the original position 
     "x":"0px", 
     "y":"0px"   
    } 

    $(this).animate({ 
     "left": "15px", 
     "top": "15px"   
    }).queue(function(next) { //after execute the animate, return to its origin position 
     $(this).css({ 
      'left': o.x, 
      'top': o.y 
     })    
     next(); 
    }); 
})​; 

或像这样:

$('#test').click(function() { //#test is the box 
    var o ={  //remember the original position 
     "x":"0px", 
     "y":"0px"   
    } 

    $(this).animate({ 
     "left": "15px", 
     "top": "15px"   
    }).queue(function() { //after execute the animate, return to its origin position 
     $(this).css({ 
      'left': o.x, 
      'top': o.y 
     }).dequeue(); 
    }); 
})​; 
这里

工作演示:http://jsfiddle.net/jfriend00/qM2CJ/

文档上.queue(fn)here

1

请尝试this演示

我用一个回调来代替。我希望我理解正确。

编辑:

下面是javascript代码:

$(function() { 
    $('#test').click(function() { 
     var o = { 
      "x": "0px", 
      "y": "0px" 
     } 

     $(this).animate({ 
      "left": "15px", 
      "top": "15px" 
     }, function() { 
      $(this).css({ 
       'left': o.x, 
       'top': o.y 
      }) 
     }); 
    }) 
})​ 
+0

最好将您的代码解决方案粘贴到您的答案中,以便人们不必去外部网站查看它。 – jfriend00

+0

@ jfriend00,编辑它。 – KiiroSora09