2013-10-10 43 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; 
});