2014-10-22 103 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