Get keyboard control events
Document. onkeydown = keyDown
When the browser reads this statement, the KeyDown () function is called no matter which key is pressed on the keyboard.
Implementation of different browsers:
Netscape
A special statement must be placed in the Netscape program to enable Netscape to always check the key-hitting event. If no such statement exists, the key-hitting event will be mixed with the mouse-clicking event. The special statement is as follows:
Document. onkeydown = keyDown
If (ns4) document. captureEvents (Event. KEYDOWN)
The keyDown () function has a hidden variable-General. We use the letter "e" to indicate this variable: function keyDown (e) variable e indicates that a key hit event occurs, find which key is pressed and use the following attributes: e. which, which gives the index value of the key and converts the index value to the letter or number value of the key: String. fromCharCode (e. which)
By putting the preceding statement together, we can know which key is pressed:
Function keyDown (e ){
Var keycode = e. which
Var realkey = String. fromCharCode (e. which)
Alert ("keycode:" + keycode + "realkey:" + realkey)
}
Document. onkeydown = keyDown
Document. captureEvents (Event. KEYDOWN)
Internet Explorer
The program of IE is similar to that of Netscape, but it does not need the e variable. event. keyCode to replace e. which: Convert the index value of the Key to the real key value. The method is similar to: String. fromCharCode (event. keyCode), the program is as follows:
Function keyDown (){
Var keycode = event. keyCode
Var realkey = String. fromCharCode (event. keyCode)
Alert ("keycode:" + keycode + "realkey:" + realkey)
}
Document. onkeydown = keyDown
Programs for both
Check the above instances in two browsers and you will find that the execution results are not always the same, because the keyboard code settings of the two browsers are different, therefore, you must use separate code to write this program separately.
We recommend that you forget the actual key value and only use the code value of the keyboard to work. The following program will be set as needed. If IE is used, ieKey will take effect and nKey will be set to 0. If Netscape is used, nKey will take effect and nKey will be set to 0, then, a warning box is used to display the values of the two:
Function keyDown (e ){
If (ns4 ){
Var nKey = e. which;
Var ieKey = 0
}
If (ie4 ){
Var ieKey = event. keyCode;
Var nKey = 0
}
Alert ("nKey:" + nKey + "ieKey:" + ieKey)
}
Document. onkeydown = keyDown
If (ns4) document. captureEvents (Event. KEYDOWN)