jQuery淡入’慢’立刻出现

我试图这样做,以便当你点击一个链接时,它删除一个div(带有一些段落和文本)并插入另一个div(带有一些段落和一些文本)。 我正在使用jQuery淡入淡出。 当您单击链接时,原始div的淡出工作,然后我有一个开关案例来确定什么被淡入。然而,fadeIn,设置为’慢’,似乎立即发生。

这是相关的代码片段(其余的只是其他情况):

$(document).ready(function() { $('.nav-link').click(function() { var linkClicked = $(this).attr("id"); $('.content').fadeOut('fast'); switch(linkClicked) { case 'home': console.log("linkClicked = "+linkClicked); $('#home-content').fadeIn('slow', function() { $(this).css("display", "inline"); $(this).css("opacity", 100); }); break; 

编辑:

因此,在将fadeTo更改为fadeOut并将fadeOut中的“slow”更改为“fast”之后,它运行良好并按照我想要的方式进行转换。 然而,每当我点击“home”时,它会将div移动到“阻挡”位置(它将它吐到左下角),然后将自己推回到容器中心的正确位置。 它只在我单击home并且没有其他sidenav链接时才这样做…这些链接都运行完全相同的代码(home只是交换机情况下的第一个)。 有任何想法吗?

如果你想在fadeIn完成后启动fadeTo ,你将需要使用回调函数。 此外,由于你渐渐变为0不透明度,只需使用fadeOut

 $(document).ready(function() { $('.nav-link').click(function() { var linkClicked = $(this).attr("id"); $('.content').fadeOut('slow', function() { // this code will begin once fadeTo has finished switch(linkClicked) { case 'home': console.log("linkClicked = "+linkClicked); $('#home-content').fadeIn('slow', function() { $(this).css("display", "inline"); $(this).css("opacity", 100); }); break; }); }); 

在没有看到你的HTML的情况下,理解你想要实现的确切结果有点困难,但这里有一个带有你上面代码的JSfiddle。

http://jsfiddle.net/W9d6t/

 $('.nav-link').click(function() { var linkClicked = $(this).attr("id"); //$('.content').fadeTo('slow', 0); switch(linkClicked) { case 'home': console.log("linkClicked = "+linkClicked); $('#home-content').fadeIn('slow', function() { $(this).css("display", "block"); alert('All done!'); }); } }); 

根据我对你要做的事情的理解,我相信你只需要这样做:

 $('#home-content').fadeIn('slow'); 

fadeIn函数自动将display属性设置为内联/块)

此外,虽然您的实现正确,但它更简单:

 $('.content').fadeOut('slow'); 

( 简化jsFiddle )

您只需要向fadeOut添加一个回调,以便在动画完成后执行:

 $(document).ready(function() { $('.nav-link').click(function() { var linkClicked = $(this).attr("id"); $('.content').fadeOut('slow', function() { switch(linkClicked) { case 'home': console.log("linkClicked = "+linkClicked); $('#home-content').fadeIn('slow', function() { $(this).css("display", "inline"); $(this).css("opacity", 100); }); break; });