检测用户何时开始/停止在jquery中输入

Amb*_*nna 9 html javascript jquery typing

一旦我为我的问题搜索解决方案,我的问题是"我想检测用户何时打字以及何时停止输入以便我可以更新状态."

我创建了一个样本.愿它适合你.

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

查看小提琴:http://jsfiddle.net/utbh575s/

Joã*_*nha 7

也许你想要的是去抖功能.

基本上它限制了函数可以触发的速率.因此它在触发事件之前等待几毫秒,就像用户停止写入过程一样.

检查此代码段

// 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) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};

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

基本上现在由你决定.用ms设置你自己的时间,你很高兴.