2012-06-20 129 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