我想在用户在文本框中完成输入后执行一个类似2秒的函数。如果他们在1秒后继续键入,延迟时间将重置为2。
它应该工作类似于自动完成框。
我知道2个事件:change和keyup。我改变的问题是,文本框必须松开焦点才能被触发。对于keyup,如果他们使用鼠标粘贴文本?
我可以在这里帮助吗?
解决方法
有HTML5 oninput事件,支持所有当前主流浏览器,可以工作到IE 8和更低:
$("#myInput").bind("input",function () {
// ...
})
> http://whattheheadsaid.com/2010/09/effectively-detecting-user-input-in-javascript(解释)
> http://whattheheadsaid.com/projects/input-special-event(plugin)
一个非常简单的跨浏览器方法是
$("#myInput").bind("input propertychange",function (evt) {
// If it's the propertychange event,make sure it's the value that changed.
if (window.event && event.type == "propertychange" && event.propertyName != "value")
return;
// Clear any prevIoUsly set timer before setting a fresh one
window.clearTimeout($(this).data("timeout"));
$(this).data("timeout",setTimeout(function () {
// Do your thing here
},2000));
});
这将使事件在IE 9中两次发生(一个用于propertychange,一个用于输入),但由于事件处理程序的性质,这没有关系。