0
0

More than 1 year has passed since last update.

contenteditableのkey入力を確認

Posted at

概要

  • contenteditableな実装を行う際、各ブラウザでキー入力の値が異なる為、判断するうえで確認するためのHTMLを記載

ソース

<html>

<head>
    <script>

        document.addEventListener('keyup', logKeyUp);
        document.addEventListener('keydown', logKeyDown);

        function logKeyUp(e) {
            console.log("keyup keyCode:" + e.keycode);
            console.log("keyup key:" + e.key);
            console.log("keyup code:" + e.code);
        }

        function logKeyDown(e) {
            console.log("keydown keyCode:" + e.keycode);
            console.log("keydown key:" + e.key);
            console.log("keydown code:" + e.code);
        }

    </script>
</head>

<body>
    <div contenteditable="true"></div>
</body>

</html>

解説

  • keydown(キーを押下したタイミング)、keyup(キーを離したタイミング)でキー入力値を確認する

IME入力時の値

Chrome 90.0.4430.212

キー入力「A」

種別 通常入力 IME入力中 IME入力確定
keyup keyCode 65 229 229
keyup key a Process Process
keyup code KeyA KeyA KeyA
keydown keyCode 65 229 229
keydown key a Process Process
keydown code KeyA KeyA KeyA

キー入力「Enter」

種別 通常入力 IME入力中 IME入力確定
keyup keyCode 13 229 229
keyup key Enter Process Process
keyup code Enter Enter Enter
keydown keyCode Enter 229 229
keydown key Enter Process Process
keydown code Enter Enter Enter
  • 上記の結果を見ると、IME入力中・IME入力確定時でkeyCode・keyは同一の為、IME入力確定時に処理をしたい、といった場合に対応できない。
    • その為、keyCodeが229 もしくはkeyがProcessの場合、codeがEnterであるか否かでIME入力確定時に処理を行うことが可能となる。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0