2014-10-22 102 views
7

一旦我爲我的問題尋找解決方案,我的問題是「我想要檢測用戶何時輸入以及何時停止輸入以便我可以更新狀態。」當用戶在jquery中啓動/停止輸入時檢測

我已經創建了一個示例。願它能爲你工作。

var typingTimer; 
var doneTypingInterval = 10; 
var finaldoneTypingInterval = 500; 

var oldData = $("p.content").html(); 
$('#tyingBox').keydown(function() { 
    clearTimeout(typingTimer); 
    if ($('#tyingBox').val) { 
    typingTimer = setTimeout(function() { 
     $("p.content").html('Typing...'); 
    }, doneTypingInterval); 
    } 
}); 

$('#tyingBox').keyup(function() { 
    clearTimeout(typingTimer); 
    typingTimer = setTimeout(function() { 
    $("p.content").html(oldData); 
    }, finaldoneTypingInterval); 
}); 



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 



<textarea id="tyingBox" tabindex="1" placeholder="Enter Message"></textarea> 
<p class="content">Text will be replace here and after Stop typing it will get back</p> 

View on Fiddle : http://jsfiddle.net/utbh575s/

+0

歡迎來到SO!你的問題是什麼? – georg 2014-10-22 08:00:54

+0

你的代碼正在工作..這個問題的目的是什麼? – rinuthomaz 2014-10-22 08:15:02

+3

嗨,是的,這是爲什麼我分享它的工作。願它對其他人也有用。 – 2014-10-30 06:58:30

回答

4

也許你想什麼反跳功能。

基本上它限制了函數可以觸發的速率。所以它在發起事件之前等待一些毫秒類似於用戶停止寫入過程。

檢查這個片段

// Returns a function, that, as long as it continues to be invoked, will not 
 
// be triggered. The function will be called after it stops being called for 
 
// N milliseconds. If `immediate` is passed, trigger the function on the 
 
// leading edge, instead of the trailing. 
 
function debounce(func, wait, immediate) { 
 
\t var timeout; 
 
\t return function() { 
 
\t \t var context = this, args = arguments; 
 
\t \t var later = function() { 
 
\t \t \t timeout = null; 
 
\t \t \t if (!immediate) func.apply(context, args); 
 
\t \t }; 
 
\t \t var callNow = immediate && !timeout; 
 
\t \t clearTimeout(timeout); 
 
\t \t timeout = setTimeout(later, wait); 
 
\t \t if (callNow) func.apply(context, args); 
 
\t }; 
 
}; 
 

 
// This will apply the debounce effect on the keyup event 
 
// And it only fires 500ms or half a second after the user stopped typing 
 
$('#testInput').on('keyup', debounce(function() { 
 
    alert('typing occurred'); 
 
    $('.content').text($(this).val()); 
 
}, 500));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="testInput" /> 
 

 
<p class="content"></p>

基本上現在就看你了。在ms設定自己的時間,你很好去。

+1

確實有用。謝謝 – Gateway 2017-04-10 22:38:22