使用setTimeout延迟执行jQuery操作的时间

29

我试图延迟交换 div 中文本的时间。它应该像一个文字幻灯片/走马灯一样工作。

由于代码有误,最终的文本替换从未发生。

此外,如何使用动画效果引入替换文本(例如窗帘)?


<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>

我认为最适合这个任务的工具是.queue() - Shikkediel
4个回答

36

.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示例


如果我在那个div里放一个<script></script>,脚本也会被刷新吗?或者还有其他什么情况。 - Vincent

9

试试这个:

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

4

您还可以使用jQuery的delay()方法来代替setTimeout()。这将使您的代码更易于阅读。以下是文档中的示例:

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

我所知道的唯一限制是它没有给你清除超时的方法。如果需要这样做,那么最好还是坚持使用所有嵌套回调,因为setTimeout会给你带来这些麻烦。


实际上,您可以使用clearQueue()来删除尚未执行的任何动画。 - Shikkediel

0
这是我解决问题的方法: 当鼠标移出菜单时(如果没有触发悬停),菜单会在几秒钟后关闭。
//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;
    });
 });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接