作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我希望输入上的事件发射器在输入输入时有轻微的延迟(冷却),例如 1 秒,因此输入一个单词会多次触发它,但在最后一次击键后仅 1 秒
我找到了这段代码
$.fn.changeOrDelayedKey = function(fn, iKeyDelay, sKeyEvent) {
var iTimeoutId,
oEventData;
// second signature used, update the variables
if (!$.isFunction(fn)) {
oEventData = arguments[0];
fn = arguments[1];
iKeyDelay = arguments[2];
sKeyEvent = arguments[3];
}
if (!iKeyDelay || 0 > iKeyDelay) {
iKeyDelay = 500;
}
if (!sKeyEvent || !this[sKeyEvent]) {
sKeyEvent = 'keydown';
}
// non-delayed event callback, should clear any timeouts, then
// call the original callback function
function fnExecCallback() {
clearTimeout(iTimeoutId);
fn.apply(this, arguments);
}
// delayed event callback, should call the non-delayed callback
// after a short interval
function fnDelayCallback() {
var that = this,
args = arguments;
clearTimeout(iTimeoutId);
iTimeoutId = setTimeout(function() {
fnExecCallback.apply(that, args);
}, iKeyDelay);
}
if (oEventData) {
this.change(oEventData, fnExecCallback);
this[sKeyEvent](oEventData, fnDelayCallback);
}
else {
this.change(fnExecCallback);
this[sKeyEvent](fnDelayCallback);
}
return this;
};
这是哪种方式,但它也会在change
上触发,这意味着如果我在5秒后没有移动焦点的情况下写一些东西,那么当我最后时,事件再次触发,这是不应该的。所以我只希望该事件发生在 keyup
事件上。
如果有人可以解释该方法是如何工作的,以及我如何修改它以适合我的用例,我将不胜感激
最佳答案
如果我了解您的用法,您可以使用 setTimeout()
和 clearTimeout()
来实现此目的:
$(function() {
var timeOut = 0;
$("#test")
.keyup(function() {
// cancel looking, the user typed another character
clearTimeout(timeOut);
// set a timeout, when user doesn't type another key
// within half a second the function is called
timeOut = setTimeout(function() {
stopptedTyping();
}, 500); // change time as needed
});
});
function stopptedTyping(){
alert('user stopped typing');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test"/>
关于javascript - 了解自定义 JQuery 事件以及如何对其进行稍微修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28392023/
我是一名优秀的程序员,十分优秀!