2013-10-10 39 views
0

我正在使用它來顯示.antwort並將動畫應用於其不透明度。這工作正常。但是,再次點擊.antwort會在沒有任何動畫的情況下立即隱藏。我究竟做錯了什麼?使用jQuery來設置動畫然後隱藏元素

jQuery(document).ready(function ($) { 
    $(".frage li").click(function() { 
     if (!$(this).find(".antwort").is(".open")) { 
      $(this).find(".antwort").css({ 
       display: "block" 
      }); 
      $(this).find(".antwort").animate({ 
       opacity: 1 
      }, 1500).addClass('open'); 
     } else { 
      $(this).find(".antwort").animate({ 
       opacity: 0 
      }, 1500).removeClass('open'); 
      $(this).find(".antwort").css({ 
       display: "none" 
      }); 
     } 
     return false; 
    }); 
}); 

回答

2

應等待要完成的動畫,分配顯示無前,否則顯示沒有人會立即生效,你贏了」無法看到動畫(該元素已被隱藏)。 使用動畫的方法的回調函數,就像這樣:

jQuery(document).ready(function ($) { 
    $(".frage li").click(function() { 
     if (!$(this).find(".antwort").is(".open")) { 
      $(this).find(".antwort").css({ 
       display: "block" 
      }); 
      $(this).find(".antwort").animate({ 
       opacity: 1 
      }, 1500).addClass('open'); 
     } else { 
      $(this).find(".antwort").animate({ 
       opacity: 0 
      }, 1500, function() { 
       // Animation complete. 
       $(this).hide() 
      }).removeClass('open'); 
     } 
     return false; 
    }); 
}); 

參考:jQuery animate API

+0

完美的答案。感謝傾斜:) –

1

這種效果可以達到只需使用fadeToggle()

$(".frage li").click(function() { 
    $(this).find(".antwort").fadeToggle(); 
    return false; 
});