浏览器键盘组合快捷键监听及坑点

872 阅读1分钟

前提

项目中开发编辑器,需求是对编辑器设定一些快捷键

需求

alt+~
alt+1
alt+2
alt+3 ...

实现

我们常规使用keyCode进行判断

document.addEventListener('keydown', function(e){
    // 主键盘
    if(e.altKey && e.keyCode == 192) { // 对应alt+~
        ...
    }
    if(e.altKey && e.keyCode == 49) { // 对应alt+1
        ...
    }
    
    if(e.altKey && e.keyCode == 50) { // 对应alt+2
        ...
    }
    ...
    
    // 小键盘
    if(e.altKey && e.keyCode == 97) { // 对应alt+1
        ...
    }
    
    if(e.altKey && e.keyCode == 98) { // 对应alt+2
        ...
    }
    ...
})

坑点

  1. keyCode 229 问题
1.  Read the virtual key code from the operating system's event information, if such information is available.
2.  If an Input Method Editor is processing key input and the event is keydown, return 229.
3.  If input key when pressed without modifiers would insert a numerical character (0-9), return the ASCII code of that numerical character.
4.  If input key when pressed without modifiers would insert a a lower case character in the a-z alphabetical range, return the ASCII code of the upper case equivalent.
5.  If the implementation supports a key code conversion table for the operating system and platform, look up the value. If the conversion table specifies an alternate virtual key value for the given input, return the specified value.
6.  If the key's function, as determined in an implementation-specific way, corresponds to one of the keys in the [table of fixed virtual key codes](https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html#fixed-virtual-key-codes), return the corresponding key code.
7.  Return the virtual key code from the operating system.
8.  If no key code was found, return 0.

参考

lists.w3.org/Archives/Pu…