# JS 鍵盤Event ## 相關函式 | 事件名 | 觸發時機 | |:----- |:------ | | onfocus | 欄位取得焦點後 | | onblur | 欄位失去焦點後 | | onchange | 欄位內容改變時 | | onkeydown | 鍵盤按下時 | | onkeyup | 鍵盤按下後放開時 | --- ## 範例 :::spoiler **keydown & keyup event** HTML ```HTML! <input type="text" id="text_input"> ``` JS ```javascript! <script> let text_input = document.getElementById("text_input"); text_input.addEventListener("keydown", function(e){ console.log("觸發了 keydown 事件, 當下欄位上的值: " + e.target.value); //console.log("觸發了 keydown 事件, 當下欄位上的值: " + this.value); }); text_input.addEventListener("keyup", function(e){ console.log("觸發了 keyup 事件, 輸入的值: " + e.target.value); //console.log("觸發了 keyup 事件, 輸入的值: " + this.value); }); </script> ``` ::: * 說明:須注意 `keydown` 和 `keyup` 因觸發時間所造成的差異。 * Demo: ![](https://i.imgur.com/zwe5Pmb.gif) ###### tags: `frontend` `jsnote` [:arrow_right: Back to Front End Homepage :arrow_left:](/S-c0eqQmS16D8tcTx4ae1g)