0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

javascriptで入力キーを取得(メモ)

Posted at

1.まずはコンソールに出力

// キーが離れたときにコンソールに出力
window.addEventListener("keyup",(e) =>{
    console.log(e.key);  
});

キーが離れたとき(keyup)コンソールに出力します。

2.文字を画面に出力

<body>
    <!--ここに文字を出力させる-->
    <div id="output"></div>
    
    <script>
        // 要素取得
        const output = document.querySelector("#output");
        
        window.addEventListener("keyup",(e) =>{ 
            // keyをHTMLで出力       
            output.innerHTML = e.key;
        });
    </script>    
</body>

入力したキーが一文字づつ出力されます。

3.入力した文字列を画面出力(配列)

<body>
    <div id="output"></div>
    
    <script>
        const array =[]; //文字格納用の配列
        const output = document.querySelector("#output");
        window.addEventListener("keyup",(e) =>{
            array.push(e.key); //配列の後ろに追加
            output.innerHTML = array;
        });
    </script>    
</body>

配列にプッシュpush()します。文字がどんどん追加されます。

4.入力した文字列を画面出力

<body>
    <div id="output"></div>
    
    <script>
        const array =[];
        const output = document.querySelector("#output");
        window.addEventListener("keyup",(e) =>{
            array.push(e.key);
            const str = array.join(""); //配列を文字列に変換
            output.innerHTML = str;
        });
    </script>    
</body>

上の例だとa,r,r,a,yみたいに出力されるので、配列の結合にjoin()を使用します。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?