如何在javascript中捕获双键按?

时间:2009-08-03 18:06:08

标签: javascript keypress

我希望能够捕获双键按下(例如Char T)以进行一些特殊处理。我希望按键发生得足够快,不能被解释为两次单独的按下,就像双击一样。 我有什么想法可以实现这个目标吗?

3 个答案:

答案 0 :(得分:19)

当按键被击中时,请记下时间。然后将其与您记下最后时间点击的时间进行比较。

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

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;
   }
}

答案 1 :(得分:10)

在按键事件发生时设置为true的变量(可能是first_press),并启动一个计时器,在一段时间后将变量重置为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);
    }
}

答案 2 :(得分: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);