前提
項目中開發(fā)編輯器啊鸭,需求是對編輯器設(shè)定一些快捷鍵
需求
alt+~
alt+1
alt+2
alt+3 ...
實現(xiàn)
我們常規(guī)使用keyCode進(jìn)行判斷
document.addEventListener('keydown', function(e){
// 主鍵盤
if(e.altKey && e.keyCode == 192) { // 對應(yīng)alt+~
...
}
if(e.altKey && e.keyCode == 49) { // 對應(yīng)alt+1
...
}
if(e.altKey && e.keyCode == 50) { // 對應(yīng)alt+2
...
}
...
// 小鍵盤
if(e.altKey && e.keyCode == 97) { // 對應(yīng)alt+1
...
}
if(e.altKey && e.keyCode == 98) { // 對應(yīng)alt+2
...
}
...
})
坑點
- 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.
參考
https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html