2012-07-11 66 views
2
$("#hi").keypress(function() { 
    $(".hi").html("Writing..."); 
}); 
$('#hi').keyup(function() { 
    $(".hi").delay(1000).queue(function() { 
     $(this).html(""); 
    }); 
}); 

當我在文本框(#hi)中輸入「Hello」時,鍵盤只適用於第一個字母,然後它不會消失。只能一次性使用鍵盤

+0

你不是真的要排隊1秒的每個按鍵的延遲? – Bergi 2012-07-11 23:34:12

回答

3

你可以使用超時,而不是延遲:

var timeout; 
$("#hi").keypress(function() { 
    // Clear any previous timeout 
    clearTimeout(timeout); 

    // Apply the writing text 
    $(".hi").html("Writing..."); 

    // Remove the text after one second if no more key is pressed until then 
    timeout = setTimeout(function() { 
     $(".hi").html(""); 
    }, 1000); 
});​ 

這裏是一個工作示例:http://jsfiddle.net/tF7DH/1/

這裏的想法是,你設置超時刪除「寫作.. 。「文字鍵擊一秒後。如果在該秒內創建了新的擊鍵,則先前的超時被清除並且設置新的超時。這樣,僅當用戶停止鍵入超過一秒鐘時纔會刪除文本。

0

我不明白爲什麼有幫助,但清除隊列會產生你你期待

$('#hi').keyup(function() { 
    console.log("keyup"); 
    $(".hi").delay(1000).queue(function() { 
     console.log("erase"); 
     $(this).html("").clearQueue(); 
    }) 
});​ 

fiddle

3

你不是通過調用next

阻斷 queue結果

從jQuery 1.4開始,被調用的函數通過另一個 函數作爲第一個參數。當被調用時,這會自動地將下一個項目出隊並保持隊列移動。我們用它作爲 如下:

$("#test").queue(function(next) { 
    // Do some stuff... 
    next(); 
});