如果要去抓到使用者輸入的特定一串內容後做一些判斷,而且不是在 input 欄位裡輸入,比如說打了 winner 這樣的內容後會跳出一個通知視窗之類的,可以利用 javascript 判斷輸入鍵盤抓取 keyCode 後轉換為實際的字串,再去判斷該字串內容就可以了。
舉例來說:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | let word = "surprise" ; let input = "" ; document.body.addEventListener( 'keypress' , function (e){ input += String.fromCharCode(e.keyCode); if (input == word){ alert(word); input = "" ; } }); // 按下 esc 後重設輸入的內容 document.body.addEventListener( 'keyup' , function (e){ if (e.keyCode == 27) input = "" ; }); |
這裡就是利用 String.fromCharCode(e.keyCode) 去抓到 keyCode 後組成新的字串去判斷,有需要的可以試試看。