2012-02-11 88 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