按小键盘时释放Shift键

时间:2019-03-25 13:33:07

标签: javascript keyboard-events

添加键盘监听器:

document.addEventListener("keydown", e=>console.log('keydown', e.code), true);
document.addEventListener("keyup", e=>console.log('keyup', e.code), true);

按Shift + Num1:

keydown ShiftLeft
keyup ShiftLeft
keydown Numpad1
keyup Numpad1
keydown ShiftLeft
keyup ShiftLeft

为什么在发送小键盘键之前不按下Shift键?是Chrome的错误吗?

document.addEventListener("keydown", e => console.log('keydown', e.code, e.shiftKey), true);
document.addEventListener("keyup", e => console.log('keyup', e.code, e.shiftKey), true);

2 个答案:

答案 0 :(得分:1)

在Windows中,Shift似乎会覆盖numlock并导致此行为。 Chrome与它无关。

https://devblogs.microsoft.com/oldnewthing/20040906-00/?p=37953

答案 1 :(得分:0)

此行为是Windows功能/怪胎。

如果要捕获shift-numpad事件,可以执行以下操作:

  1. 松开Shift键时保存时间戳
  2. 在您的按键事件中,检查事件发生多久了。如果少于50毫秒左右,则用户很有可能按下Shift +数字键(而不是箭头键)。

    let iShiftReleaseTime;
    
    $(document).keyup(function (e) {
        if(e.keyCode == 16) //shift key
            iShiftReleaseTime = Date.now();
    });
    
    $(document).keydown(function (e) {
        if ((Date.now() - iShiftReleaseTime) < 50) {
            if (e.keyCode == 45) console.log("Shift + Numpad 0 was pressed");
            if (e.keyCode == 35) console.log("Shift + Numpad 1 was pressed");
            if (e.keyCode == 40) console.log("Shift + Numpad 2 was pressed");
            if (e.keyCode == 34) console.log("Shift + Numpad 3 was pressed");
            if (e.keyCode == 37) console.log("Shift + Numpad 4 was pressed");
            if (e.keyCode == 12) console.log("Shift + Numpad 5 was pressed");
            if (e.keyCode == 39) console.log("Shift + Numpad 6 was pressed");
            if (e.keyCode == 36) console.log("Shift + Numpad 7 was pressed");
            if (e.keyCode == 38) console.log("Shift + Numpad 8 was pressed");
            if (e.keyCode == 33) console.log("Shift + Numpad 9 was pressed");
        }
        else {
            if (e.keyCode == 37) console.log("left arrow key was pressed");
            if (e.keyCode == 38) console.log("up arrow key was pressed");
            if (e.keyCode == 39) console.log("right arrow key was pressed");
            if (e.keyCode == 40) console.log("down arrow key was pressed");
            //etc...
        }
    });