2016-08-22 61 views
6

我有6個「塊」,而且每個包含不同的文本,爲簡單起見,我們只考慮這些作爲我的「塊」如何在每次點擊時都反轉動畫?

<div id="block1"> <h2> Block1 </h2> </div 

我對他們有3可見和3隱藏。我有一個按鈕,取代相應的塊

$(".showmore").click(function(){ 

    $("#block1").fadeOut("slow", function(){ 
     $(this).replaceWith($("#block4").html()); 
     $(this).fadeIn("slow"); 
    }); 

    $("#block2").delay(400).fadeOut("slow", function(){ 
     $(this).replaceWith($("#block5").html()); 
     $(this).fadeIn("slow"); 
    }); 

    $("#block3").delay(800).fadeOut("slow", function(){ 
     $(this).replaceWith($("#block6").html()); 
     $(this).fadeIn("slow"); 
    }); 

    $(this).text('Show less'); 

}); 

它工作正常,但不知道如何恢復它。我試圖將元素克隆到一個變量,然後加載它們,但似乎id已經消失,因爲當我試圖隱藏block1或block4時,它們都沒有消失。誰能幫忙?

+0

請添加更多HTML代碼,或者在jsfiddle上提供代碼 –

+0

相關http://stackoverflow.com/questions/2132090/jquery-reversing-animation-on-second-click http://stackoverflow.com/questions/ 27166633 /第二次點擊反向動畫 – yuriy636

回答

1

據我所知,你有3個div,你想恢復他們的內容,他們有一個淡出/淡入淡出事件後點擊另一個股利。您嘗試的問題是使用replaceWith方法。這是你想要達到的目標嗎?請參閱小提琴here

$(".showmore").click(function(){ 
    $("#block1").fadeOut("slow", function(){ 
     //save the content of the hidden block to a variable 
      var html = $("#block4").html(); 
     //put the content of the current div to the hidden div, to be used on the next click 
     $("#block4").html($(this).html()); 
     //show the content of the hidden div 
     $(this).html(html); 
     $(this).fadeIn("slow"); 
    }); 

    $("#block2").delay(400).fadeOut("slow", function(){ 
     var html = $("#block5").html(); 
     $("#block5").html($(this).html()); 
     $(this).html(html); 
     $(this).fadeIn("slow"); 
    }); 

    $("#block3").delay(800).fadeOut("slow", function(){ 
     var html = $("#block6").html(); 
     $("#block6").html($(this).html()); 
     $(this).html(html); 
     $(this).fadeIn("slow"); 
    }); 

    $(this).text('Show less'); 

}); 

正如您所見,我將div的內容複製到相應的隱藏區域。像這樣,你可以在每次點擊時切換數據。

+0

我需要這個,非常感謝! – Paralyz3d

+0

很高興幫助你:) – avi

0

一個想法是fadeoutfadein而不是replaceWith。 然後您可以檢查哪個塊可見,哪個不可見。

var visible, invisible; 
if ($("#block1").is(":visible")) { 
    visible = "#block1"; 
    invisible = "#block4"; 
} else { 
    visible = "#block4"; 
    invisible = "#block1"; 
} 
$(visible).fadeOut("slow", function(){ 
    $(invisible).fadeIn("slow"); 
}); 

不知道這是否給你相同的功能,雖然。