簡體   English   中英

使用setTimeout來延遲jQuery操作的時間

[英]Using setTimeout to delay timing of jQuery actions

我試圖延遲在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>

.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強加給你的所有嵌套回調。

這就是我解決問題的方法菜單在鼠標輸出幾秒后關閉(如果懸停沒有觸發),

//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;
    });
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM