使用setTimeout来延迟jQuery操作的时间

我试图延迟div中文本的交换。 它应该像文本的滑块/旋转木马一样操作。

我必须把代码弄错,因为最终的文本替换永远不会发生。

另外,我如何动画引入替换文本(例如,窗帘)?


      $(document).ready(function() { $("#showDiv").click(function() { $('#theDiv').show(1000, function() { setTimeout(function() { $('#theDiv').html('Here is some replacement text', function() { setTimeout(function() { $('#theDiv').html('More replacement text goes here'); }, 2500); }); }, 2500); }); }); //click function ends }); //END $(document).ready()    Below me is a DIV called "theDiv".

This text is inside the Div called "theDiv".


.html()只接受字符串或函数作为参数, 而不是两者 。 试试这个:

  $("#showDiv").click(function () { $('#theDiv').show(1000, function () { setTimeout(function () { $('#theDiv').html(function () { setTimeout(function () { $('#theDiv').html('Here is some replacement text'); }, 0); setTimeout(function () { $('#theDiv').html('More replacement text goes here'); }, 2500); }); }, 2500); }); }); //click function ends 

jsFiddle示例

试试这个:

 function explode(){ alert("Boom!"); } setTimeout(explode, 2000); 

您还可以使用jQuery的delay()方法而不是setTimeout() 。 它会为您提供更易读的代码。 以下是文档中的示例:

 $( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 ); 

唯一的限制(我知道)是它没有给你一种方法来清除超时。 如果你需要这样做那么你最好坚持使用setTimeout强加给你的所有嵌套回调。

这就是我解决问题的方法鼠标输出后几秒钟菜单关闭(如果hover没有触发),

 //Set timer switch $setM_swith=0; $(function(){ $(".navbar-nav li a").click(function(event) { if (!$(this).parent().hasClass('dropdown')) $(".navbar-collapse").collapse('hide'); }); $(".navbar-collapse").mouseleave(function(){ $setM_swith=1; setTimeout(function(){ if($setM_swith==1) { $(".navbar-collapse").collapse('hide'); $setM_swith=0;} }, 3000); }); $(".navbar-collapse").mouseover(function() { $setM_swith=0; }); });