Skip to content

Instantly share code, notes, and snippets.

@cesarkohl
Forked from asika32764/detectKeyPress.js
Last active August 29, 2015 14:10
Show Gist options
  • Save cesarkohl/5b7dce0af050de486056 to your computer and use it in GitHub Desktop.
Save cesarkohl/5b7dce0af050de486056 to your computer and use it in GitHub Desktop.
/*
* 判斷按下的按鈕是哪一個
* @param (event) e keypress event.
* @param (mix) targetKeyChar 按鍵的編號或名稱,如果是這個按鍵,就執行 callback
* @param (function) callBack 送入callback的function,不用加()括號
*
*/
var detectKeyPress = function(e, targetKeyChar, callBack){
var keynum
var keychar
var numcheck
if(window.event) // For IE
{
keynum = e.keyCode
}else if(e.which) // For Netscape/Firefox/Opera
{
keynum = e.which
}
keychar = String.fromCharCode(keynum)
if( typeOf(targetKeyChar) == 'string' ) {
if(targetKeyChar == keychar) {
callBack() ;
}
}else{
if(targetKeyChar == keynum) {
callBack() ;
}
}
}
<input onkeypress="detectKeyPress(event, 'a', callBackFunction );" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment