2012-04-28 88 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