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

css*_*hus 27 javascript jquery

我试图延迟在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>
Run Code Online (Sandbox Code Playgroud)

j08*_*691 29

.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
Run Code Online (Sandbox Code Playgroud)

jsFiddle例子


小智 7

试试这个:

function explode(){
  alert("Boom!");
}
setTimeout(explode, 2000);
Run Code Online (Sandbox Code Playgroud)