2014-10-01 56 views
2

这是我的第一篇文章在这里。我搜查了很多,但我还没有发现任何关于此。javascript:jQuery的replaceWith()不尊重延迟()

我无法按预期工作这个脚本(它在运行时错误):

(function ($) { 
    $("div#replace").click(function() { 
     $(this).fadeOut("200").delay("200").replaceWith("<div id='replace'>new content</div>").delay("200").fadeIn("200"); 
    }); 
})(jQuery); 

我是从DIV#希望这种替换:

淡出 - >更改内容 - >淡入

相反,我得到了这种行为:

变化的内容 - >淡出 - >淡入


[编辑]谢谢你们,我有一个解决方案。我在这里发布它:

我使用Spokey的方法,并且从replaceWith()切换到了html(),它使fadeIn动画正常工作。

$("div#replace").click(function() { 
    $(this).fadeOut("200", function() { 
     $(this).html("new content").fadeIn("200"); 
    }); 
}); 

谢谢!对不起我的英文不好:)

+0

尝试用'的.html的()''而不是replaceWith()' – 2014-10-01 09:42:42

+0

这就是为什么你必须'callbacks'使用。 – melancia 2014-10-01 09:42:59

回答

0

您可以使用fadeOut回调(淡入淡出完成时)来替换div,然后再次显示它。

(function ($) { 
    $("div#replace").click(function() { 
     $(this).fadeOut("200", function(){ 
      $(this).replaceWith("<div id='replace'>new content</div>").fadeIn("200"); 
     }); 
    }); 
})(jQuery); 
1

replaceWith()没有绑定到动画队列,所以delay()不会影响它的行为。

你可以,但是,使用queue()dequeue()扳平任意代码到动画队列:

$(this).fadeOut("200").delay("200").queue(function(next) { 
    $(this).replaceWith("<div id='replace'>new content</div>"); 
    next(); 
}).delay("200").fadeIn("200"); 

请注意,我用queue()提供的next方法,发出信号,未来动画的步骤就可以开始,而不是链接到dequeue()在我原来的答案。

这是因为dequeue()依赖于匹配的元素,并且因为replaceWith()从DOM中删除这些元素,我不是100%正面dequeue()会对它们起作用。