13

我希望能够捕获双按键(例如对于 Char T)以进行一些特殊处理。我希望按键发生的速度足够快,不会被解释为两个单独的按键,就像双击。有什么想法我能做到这一点吗?

4

3 回答 3

26

击键时,记下时间。然后将其与您记录的最后一次按键的时间进行比较。

如果差异在您的阈值之内,请将其视为双倍。否则,不要。粗略的例子:

var delta = 500;
var lastKeypressTime = 0;
function KeyHandler(event)
{
   if ( String.fromCharCode(event.charCode).toUpperCase()) == 'T' )
   {
      var thisKeypressTime = new Date();
      if ( thisKeypressTime - lastKeypressTime <= delta )
      {
        doDoubleKeypress();
        // optional - if we'd rather not detect a triple-press
        // as a second double-press, reset the timestamp
        thisKeypressTime = 0;
      }
      lastKeypressTime = thisKeypressTime;
   }
}
于 2009-08-03T18:08:04.220 回答
12

有一个first_press在按键事件发生时设置为 true 的变量(可能是 ),并启动一个计时器,该计时器将在设定的时间后将变量重置为 false(无论您希望他们按下按键的速度有多快)。

在您的按键事件中,如果该变量为真,那么您可以双击。

例子:

var first_press = false;
function key_press() {
    if(first_press) {
        // they have already clicked once, we have a double
        do_double_press();
        first_press = false;
    } else {
        // this is their first key press
        first_press = true;

        // if they don't click again in half a second, reset
        window.setTimeout(function() { first_press = false; }, 500);
    }
}
于 2009-08-03T18:08:14.173 回答
0

我知道回答为时已晚,但我是这样实现的:

let pressed;
let lastPressed;
let isDoublePress;

const handleDoublePresss = key => {
    console.log(key.key, 'pressed two times');
}

const timeOut = () => setTimeout(() => isDoublePress = false, 500);

const keyPress = key => {
    pressed = key.keyCode;

    if (isDoublePress && pressed === lastPressed) {
        isDoublePress = false;
        handleDoublePresss(key);
    } else {
        isDoublePress = true;
        timeOut();
    }

    lastPressed = pressed;
}

window.onkeyup = key => keyPress(key);
于 2019-04-05T12:36:07.883 回答