2008-11-29 92 views
74

我正在加載JSON數據到我的頁面和使用appendTo(),但我想淡入我的結果,任何想法?使用淡入淡出和追加

$("#posts").fadeIn(); 
$(content).appendTo("#posts"); 

我看到append和appendTo在文檔上有區別。

我嘗試這樣做,以及:

$("#posts").append(content).fadeIn(); 

我得到了它,上面的伎倆!

但我得到「未定義」作爲我的JSON值之一。

回答

168

如果您在追加內容並將fadeIn方法鏈接到該內容之前隱藏了內容,則應該獲得所需的效果。

// Create the DOM elements 
$(content) 
// Sets the style of the elements to "display:none" 
    .hide() 
// Appends the hidden elements to the "posts" element 
    .appendTo('#posts') 
// Fades the new content into view 
    .fadeIn(); 
+2

謝謝你的幫助凱文 – Coughlin 2008-11-30 05:09:30

+1

工作很好,謝謝。 – cweston 2009-07-02 05:04:57

3

您必須知道代碼不會線性執行。動畫的東西不能期望停止代碼執行動畫,然後返回。


    commmand(); 
    animation(); 
    command();

這是因爲動畫使用set timeout和其他類似的魔術來完成它的工作,並且settimeout是非阻塞的。

這就是爲什麼我們對動畫的回調方法,當動畫完成(以避免改變一些東西,還不存在)

 
    command(); 
    animation(... function(){ 
     command(); 
    }); 
7

我不知道我完全理解這個問題上運行你有,但這樣的事情應該工作:

HTML:

<div id="posts"> 
    <span id="post1">Something here</span> 
</div> 

的Javascript:

var counter=0; 

$.get("http://www.something/dir", 
    function(data){ 
     $('#posts').append('<span style="display:none" id="post' + counter + ">" + data + "</span>") ; 
     $('#post' + counter).fadeIn(); 
     counter += 1; 
    }); 

基本上你包裹每件作品的跨度的含量(每「後」),創下跨度的顯示屏無法比擬的,因此不會顯示出來,然後逐漸把它。

4

這應該解決你的問題,我想。

$('#content').prepend('<p>Hello!</p>'); 
$('#content').children(':first').fadeOut().fadeIn(); 

如果你正在做append,那麼你必須使用:last selector。

2

假設你已經定義的CSS如下:

.new {display:none} 

和JavaScript應該是:

$('#content').append('<p class='new'>Hello!</p>'); 
$('#content').children('.new').fadeIn(); 
$('#content').children.removeClass('new'); 
$('#content').children('.new').hide(); 
1

首先是接收到的數據轉換爲jQuery對象。其次,立即隱藏它。 第三,將其追加到目標節點。 而且,在這一切之後,我們可以清楚地使用必要的動畫,就像淡入:)

jNode = $("<div>first</div><div>second</div>"); 
jNode.hide(); 
$('#content').append(jNode); 
jNode.fadeIn(); 
0

IM有exprensive,對於這個:

$("dt").append(tvlst.ddhtml); 
$("dd:last").fadeIn(700); 
3
$(output_string.html).fadeIn().appendTo("#list");