2013-06-05 35 views
22

我正在尝试延迟文本在div中的交换。它应该像文本的滑块/旋转木马一样操作。使用setTimeout延迟jQuery动作的时间

我必须有错误的代码,因为最终的文本替换从未发生过。

此外,我将如何动画介绍替代文字(窗帘,例如)?


<html> 
    <head> 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
     <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> 
     <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" /> 

     <script type="text/javascript"> 
$(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() 

     </script> 
    </head> 
<body> 

    Below me is a DIV called "theDiv".<br><br> 
    <div id="theDiv" style="background-color:yellow;display:none;width:30%;margin:0 auto;"> 
     This text is inside the Div called "theDiv". 
    </div><br> 
    <br> 
    <input type="button" id="showDiv" value="Show DIV"> 



</body> 
</html> 
+0

最合适工具为''.queue()'我认为... – Shikkediel

回答

24
.html()

只需要一个字符串或作为参数,not both的功能。试试这个:

$("#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 example

+0

如果我把放在那个div里面,脚本也会被刷新吗?或者其他的东西。 – Vincent

2

您还可以使用jQuery's delay() method而不是setTimeout()。它会给你更多可读的代码。下面是从文档的例子:

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

唯一的限制(即我所知道的)是它不给你一个方法来清除超时。如果你需要这样做,那么你最好坚持使用所有嵌入的回调函数。

+0

实际上,你可以使用'clearQueue()'去除尚未执行的任何动画。 – Shikkediel

7

试试这个:

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

这是我如何解决 菜单鼠标了(如果悬停不火)关闭后几秒钟的问题,

$setM_swith=0; //Set timer switch 
$(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; 
     }); 
    }); 
+0

对不起,错的地方:( –