2012-02-11 85 views
1

我试图在标题中尽可能详细,但它总是模糊不清。所以,我会阐述在这里:为多个元素创建一个同步动画

我有以下HTML:

​<span class="item c1"><!--content--></span> 
<span class="item c2"><!--content--></span> 
<span class="item c3 c2"><!--content--></span> 
<span class="item c1"><!--content--></span> 
<span class="item c1 c4"><!--content--></span>​ 

好吧,假设<!--content-->的大小始终是不同的,其中 - 在这种情况下 - 意味着在同样宽度元素将会不同。

所以,我需要做的是以某种方式“过滤”他们的内容类。基本上我需要让他们消失,并在筛选器被选中时重新出现。

我让他们消失的方法是使用jQuery的.animate()其宽度0px和不透明度设置为0 —这一切发生的过渡性。

当下DOM负载,我自己的“原创”宽度保存到data-*属性:

jQuery(function(){ 

    jQuery('.item').each(function(i, e) { 
     var $e = jQuery(e); 
     $e.data('origWidth', $e.css('width')); 
    }); 

}); 

现在,正在被再次显示,当他们(或重新过滤,如果你愿意)他们都得到同样的宽度(我知道为什么,但我不知道它周围的路):

jQuery('.c'+id+'.item').stop().animate({ 
    'width' : jQuery('.c'+id+'.item').data('origWidth'), 
    'opacity' : 1 
}); 
//NOTE: the [id] in the above snippet is passed by a 
//function and is the category id. 

那么,什么我的“真实”的问题是:有没有一种方法来同步通过一个jQuery数组迭代,动画属性–或沿着这些线的东西。

谢谢!

+2

'$ e.css( '宽')'和'$ e.width取代它()'和'的jQuery(” C - '+ id +'。item')'vs'jQuery('。c'+ id +'。item')'typo? – Cheery 2012-02-11 20:12:42

+0

你可以在jsfiddle.net上设置一个例子吗? – Richard 2012-02-11 20:21:38

回答

2

好吧,只是几个字..你没有记住每个元素的宽度。 jQuery的动画可以为你做。简单的例子:http://jsfiddle.net/AkJAm/3/

<span class='item'>Some content</span> 
<span class='item'>Another content</span> 
<span class='item'>And so on</span> 

<br /> 
<a href='#' id='animate'>Click me</a> 

和JS代码:

$(document).ready(function(){ 
    $('#animate').click(function(){ 
     $('.item').animate({width: 'toggle', opacity: 'toggle'}); 
     return false; 
    }); 
}); 
+0

我只是编辑你的文章添加点,但你打败了我:-)好的解决方案! – Richard 2012-02-11 20:31:37

+0

啊,谢谢!我不知道“toggle”功能。 – omninonsense 2012-02-12 14:01:09

1

的所有

jQuery('.item').each(function(i, e) { 
    var $e = jQuery(e); 
    $e.data('origWidth', $e.css('width')); 
}); 

首先应该是

jQuery('.item').each(function() { 
    jQuery(this).data('origWidth', jQuery(this).width()); 
}); 

什么行动使他们重新出现或者被过滤?

我认为你缺少动画的持续时间..

jQuery('.c-'+id+'.item').stop().animate({ 
    'width' : jQuery('.c'+id+'.item').data('origWidth'), 
    'opacity' : 1 
}, 1000); 

而且.item似乎是多余的,所以:

jQuery('.c-' + id).stop().animate({ 
    'width' : jQuery('.c' + id).data('origWidth'), 
    'opacity' : 1 
}, 1000); 

更新:

所以回到你的问题:

所以,我的”真正“问题是:有没有一种方法可以同步迭代jQuery数组并为这些属性设置动画效果 - 或者沿着这些线条进行设置。

你需要通过他们迭代?

这难道不是工作?

jQuery('.c-' + id).stop().animate({ 
    'width' : 'toggle', // courtesy of @Cheery 
    'opacity' : 1 
}); 

以及使用slideUpslideDownslideToggle什么?

+0

'我想你错过了动画的持续时间'默认持续时间是400毫秒,可以省略。 – Cheery 2012-02-11 20:18:58

+0

好的,谢谢!忘记了那个 – Richard 2012-02-11 20:20:15