【问题标题】:Detect when user is starting/stopping typing in jquery检测用户何时开始/停止输入 jquery
【发布时间】:2014-10-22 07:55:40
【问题描述】:

有一次我正在为我的问题寻找解决方案,而我的问题是“我想检测用户何时输入以及何时停止输入,以便我可以更新状态。”

我创建了一个示例。愿它对你有用。

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/

【问题讨论】:

  • 欢迎来到 SO!你有什么问题?
  • 您的代码正在运行。这个问题的目的是什么?
  • 嗨,是的,我分享它的原因是它的工作原理。愿它对其他人也有用。
  • 然后回答问答式。为什么要把它放在问题中?

标签: javascript jquery html typing


【解决方案1】:

也许您想要的是 debounce 功能。

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

检查这个sn-p

// 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));
<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 为单位设置您自己的时间,一切顺利。

【讨论】:

  • 确实有用。谢谢
猜你喜欢
  • 1970-01-01
  • 2015-06-28
  • 2017-07-02
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
  • 2015-09-22
  • 2023-04-05
相关资源
最近更新 更多