瀏覽器鍵盤組合快捷鍵監(jiān)聽及坑點(diǎn)

前提

項(xiàng)目中開發(fā)編輯器,需求是對編輯器設(shè)定一些快捷鍵

需求

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

實(shí)現(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
        ...
    }
    ...
})

坑點(diǎn)

  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.

參考

https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容