2012-04-28 89 views
2

我有5個圖像,點擊時我試圖將它們相鄰,相距50px進行動畫處理。每個以前的元素jQuery margin-left

目前我正在動畫第一個孩子,剩下的所有其他人都是50px,但所有人都在彼此之上。

這裏是我的腳本:

var fadedur = 200, 
    fadeop = 0.5, 
    imgwidth = 220, 
    imgleft = 40, 
    imgfirst = -200, 
    imgfh = -100; 

$('img').on('click', function(){ 
    $('img').css('position','absolute').css('display','block'); 

    $('.cs').find(':first-child').stop().animate({ 
      "marginLeft": imgfirst, 
      "margin-top": imgfh, 
     }, 300); 

    $('.cs').find(':first-child').next('img').each(function() {   
     $(this).stop().animate({ 
      "marginLeft": imgfirst + imgwidth + imgleft, // imgfirst should 
      "margin-top": imgfh,       // be something that 
     }, 300);           // states prev() 
    }); 

});​ 

,這是我的小提琴:http://jsfiddle.net/STgQC/

我試圖讓他們看起來像這樣:

enter image description here

所以基本上我需要東西會說:

動畫到上一個元素的位置+圖像寬度+ 50px左側。

回答

2

$('.cs').find(':first-child').next('img')最多隻能匹配一個元素,因此無意中每個元素都會調用它。
看看這個更新的小提琴http://jsfiddle.net/STgQC/1/,這是你正在尋找的行爲?

+1

如果第一圖像* *需要做一些不同的東西,你也可以使用.nextAll( 'IMG')來在第一個圖像之後獲得完整的圖像集合。 – samiz 2012-04-28 00:45:24

2

.each()遍歷next()的結果。在你的情況下,next()只返回第一個圖像。所以,你的代碼只能迭代1個圖像。

我會將2次迭代合併爲1次邏輯。

試試下面的(成功):
還撥弄在這裏:http://jsfiddle.net/FranWahl/mYRdU/1/

var fadedur = 200, 
    fadeop = 0.5, 
    imgwidth = 220, 
    imgleft = 40, 
    imgfirst = -200, 
    imgfh = -100; 

$('img').on('click', function(){  
    $('img').css('position','absolute').css('display','block'); 

    var newLeft = imgfirst; 

    $('.cs').find('img').each(function(){ 
     $(this).stop().animate({ 
      "marginLeft": newLeft,//imgfirst + imgwidth + imgleft, 
      "margin-top": imgfh, 
     }, 300); 

     newLeft += imgwidth + imgleft; 
    });     
});​ 
+0

你的回答正是我所期待的,但是穆薩首先回答了一個正確的解決方案,所以我將接受他的答案作爲我的問題的解決方案。謝謝。 – jQuerybeast 2012-04-28 00:41:47