最后按下的键事件

Last key pressed event?

本文关键字:事件 最后      更新时间:2023-09-26

如何知道用户停止输入?

像这样:

$('#input').onkeyup(function(){
   //do something
});

但是你怎么知道那是不是最后一次.onkeyup事件呢?

我认为需要一个计时器,知道用户何时停止打字可以在最后一个.onkeyup后2秒…诸如此类。

想法?

是的,你是对的…您可以使用基于定时器的解决方案,如

jQuery(function ($) {
    //to store the reference to the timer
    var timer;
    $('#myinput').keyup(function () {
        //clear the previous timer
        clearTimeout(timer);
        //create a new timer with a delay of 2 seconds, if the keyup is fired before the 2 secs then the timer will be cleared
        timer = setTimeout(function () {
            //this will be executed if there is a gap of 2 seconds between 2 keyup events
            console.log('last')
        }, 2000);
    });
})

演示:小提琴