身為十幾年前開始學 JavaScript 的老人,腦中總有些過時的觀念與知識,就像聊天時偶爾會脫口說出小叮噹、神奇寶貝般不合時宜,當場曝露年紀。

昨天談到 Chromium keydown Bug,讀者 Chester Fung 提醒,keydown/keyup 事件中已不該再用 keyCode 取得按鍵值,查了一下,真是如此!

MDN: KeyboardEvent: keyCode property

依據官方文件建議,keyCode 的嫌惡等級為:「如果可能,請避免使用」[1]、「如果可能,有用它的程式碼也改一下吧」[2]。

keyCode 的主要問題在於部分特殊鍵在不同的瀏覽器和不同平台(Windows、Mac、Linux)的結果不一致,MDN 文件有提供對照表,如下圖可以找到一些不同瀏覽器不同 OS 結果不同的案例:

知道 keyCode 將作廢,要改用 KeyboardEvent.codeKeyboardEvent.key 倒也沒啥難度。我寫了一個簡單範例:線上測試

<!DOCTYPE html>
<html>
<head>
    <title>KeyboardEvent code and key test</title>
</head>
<body>
    <textarea placeholder="type something here" rows="4" cols="40"></textarea>
    <ul></ul>
    <script>
        document.querySelector('textarea').addEventListener('keydown', function (event) {
            var ul = document.querySelector('ul');
            var li = document.createElement('li');
            li.appendChild(document.createTextNode(`code: ${event.code}, key: ${event.key}`));
            ul.appendChild(li);
        });
    </script>

</body>
</html>

code 改以字串表示,不再需要用數字查表,ShiftLeftArrowLeft 一目瞭然,對開發者十分友善。

未來再寫到 keydown、keyup 就別再用 keyCode 了,跟上時代的腳步吧。
(所以開發知識不只是要學會,還必須時時 Update,累~~~)

The article discusses the outdated use of keyCode for handling keyboard events in JavaScript and recommends switching to KeyboardEvent.code and KeyboardEvent.key for better consistency across different browsers and platforms. It also provides a simple example to illustrate the ease of using the newer properties.


Comments

Be the first to post a comment

Post a comment