JavaScript key events

Source: Internet
Author: User
Tags key string numeric value printable characters

  This article is mainly on the JavaScript key events in a detailed summary of the introduction, the need for friends can come to the reference, I hope to help you.

The first part: The browser's key events     with JS to achieve keyboard records, to pay attention to the browser three types of key events, namely Keydown,keypress and KeyUp, they correspond to onkeydown, onkeypress and onkeyup These three event handles. A typical button will produce all three events, followed by Keydown,keypress, and then the KeyUp when the button is released.     In these 3 event types, KeyDown and KeyUp are relatively low-level, and keypress are more advanced. The so-called advanced point is that when the user presses SHIFT + 1 o'clock, KeyPress is able to parse the key event to return a printable "!" characters, and KeyDown and KeyUp just record the SHIFT + 1 event. [1]    But keypress can only be valid for some printable characters, but for function keys such as F1-F12, Backspace, Enter, Escape, PageUP, PageDown, and arrow direction, KeyPress events are not generated, but KeyDown and KeyUp events can occur. However, in Firefox, the function keys can produce keypress events.     Event objects passed to the KeyDown, KeyPress, and KeyUp event handles have some common properties. If ALT, CTRL, or shift are pressed together with a key, this is represented by the Altkey, Ctrlkey, and Shiftkey properties of the event, which are common in Firefox and IE.     Part II: Compatible browsers     All browser-related JS, you have to consider the problem of browser compatibility.   currently commonly used browsers are mainly based on IE and based on Mozilla two major categories. Maxthon is based on the IE kernel, and Firefox and Opera are based on the Mozilla kernel.     2.1 Event initialization     The first thing you need to know is how to initialize the event, the basic statement follows:    function KeyDown () {}  Document.onke Ydown = keydown;    When the browser reads this statement, the KeyDown () function is called regardless of which key is pressed on the keyboard.     2.2 Firefox andOpera's implementation methods     Firefox and opera, such as program implementation than IE trouble, so here first describe. The     KeyDown () function has a hidden variable--in general, we use the letter "E" to represent this variable.     function KeyDown (e)     variable e indicates that a keystroke event occurred, looking for which key was pressed, to use which this property:    e.which    E.which will give the index value of the key, the method that converts the index value to the letter or numeric value of the key needs to use the static function String.fromCharCode (), as follows:    String.fromCharCode (E.which)     Put the above statement together, we can get in Firefox is pressed which key:      code as follows: function KeyDown (e) {  var Keyco de = e.which;  var realkey = String.fromCharCode (E.which);  alert ("Key code:" + KeyCode + "character:" + Real Key); }  Document.onkeydown = keydown;    2.3 IE implementation method     IE program does not require e-variable, with Ycode instead of E.which, the index value of the key is converted to a true key-value method similar to the following: String.fromCharCode (Event.keycode), the program follows:    code as follows: function KeyDown () {&       nbsp var keycode = event.keycode;  var realkey = String.fromCharCode (event.keycode);  alert ("Key code:" + Key Code + "character:" + Realkey); &nbsP }  Document.onkeydown = keydown;    2.4 To determine browser type     The above understanding how to achieve the method of getting the key event object in various browsers, the following needs to determine the browser type , this method many, has the more convenient understanding, also has the very ingenious method, first says the general way: is uses the Navigator object The AppName attribute, certainly also may use the useragent attribute, here uses the appname to realize the Judgment browser type, IE and Maxthon's appname are "Microsoft Internet Explorer", while Firefox and opera appname are "Netscape", so a simpler code is the following:            The code is as follows: function KeyUp (e) {  if (navigator.appname = "Microsoft Internet Explorer")   {        var keycode = event.keycode;  var realkey = String.fromCharCode (event.keycode);        {  var keycode = e.which;  var realkey = String.fromCharCode (E.which); }  Alert ("Key code:" + KeyCode + "character:" + Realkey); }  document.onkeyup = keyup;    Simpler method is [ 2]:    Code as follows: function KeyUp (e) {  var currkey=0,e=e| | event;  currkey=e.keycode| | e.which| | e.charcode;  var keyname = String.fromchaRcode (Currkey);  alert ("Key code: + Currkey +" character: "+ keyname); }  document.onkeyup = Keyup;&nbs P   Above this method is more ingenious, simply explain:  first, e=e| | event; This code is for compatibility with browser event object acquisition. JS in this code means that if in Firefox or opera, the hidden variable e is there, then e| | Event returns E, if in IE, the hidden variable e does not exist, then the event is returned.   Second, currkey=e.keycode| | e.which| | E.charcode this sentence is to be compatible with the browser key event object key code attributes (see the third part), such as IE, only keycode properties, and Firefox has which and CharCode properties, Opera has keycode and which attributes.     The above code is only compatible with browsers, get the KeyUp event object, a simple pop-up button code and the character of the key, but the problem arises, when you press the button, the word keys are uppercase, and press SHIFT, the characters appear very strange, so you need to optimize the code.     Part III: Code implementation and optimization     3.1 key event keys and character codes     key event key code and character code lack of portability between browsers, for different browsers and different case events, Key code and character code are stored in different ways,....... In IE, there is only one keycode attribute, and its interpretation depends on the event type. For KeyDown, KeyCode stores the key code, and for the KeyPress event, KeyCode stores a character code. The which and CharCode properties are not in IE, so the which and CharCode properties are always undefined.     Firefox keycode is always 0, time Keydown/keyup, Charcode=0,which for key code. Event KeyPress, which and charcode both have the same value, and the character code is stored.     In opera, the values of keycode and which are always the same, and in the Keydown/keyup event, they store key code,In keypress time, they store character codes, and charcode are not defined, always undefined.     3.2 with Keydown/keyup or keypress    The first part has introduced the difference between Keydown/keyup and KeyPress, there is a more general rule, The KeyDown event is most useful for function keys, and the KeyPress event is most useful for printable keys [3].     Keyboard records are mainly for printable characters and some function keys, so keypress is preferred, however, as mentioned in the first part, IE KeyPress does not support the function button, so it should be supplemented with Keydown/keyup event.     3.3 Code implementation   Overall thinking, with the KeyPress event object to get the key characters, using KeyDown event to obtain functional characters, such as Enter,backspace. The     code implementation is as follows     code as follows:! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >  <HTML>  <head><title>js Key record </TITLE>  <meta name= "generator" content= "EditPlus" >  <meta name= "Author" content= "Feather-yan" >  <meta name= "Keywords" content= "JS key record" >  <meta name= "Description" content= "JS key Record" >   </HEAD>  <BODY>  <script type= "Text/javascript" >  var keystring = "";/ Record key string   function $ (s) {return document.getElementById (s)? document.getElementById (s): s;}  function KeyPress (e)   {  var currkey=0,capslock=0,e=e| | event;  currkey=e.keycode| | e.which| | e.charcode;  capslock=currkey>=65&&currkey<=90;  switch (currkey)   { //shielding BACKSPACE, System     Tables, carriage returns, spaces, directional keys, delete keys   case 8:case 9:case 13:case 32:case 37:case 38:case 39:case 40:case 46:keyname = "";break;  Default:keyname = String.fromCharCode (Currkey); break; }  keystring + = keyname; }  function KeyDown (e)   {  var e=e| | event;  var currkey=e.keycode| | e.which| | e.charcode;  if ((currkey>7&&currkey<14) | | (currkey>31&&currkey<47))   {  switch (currkey)   {  Case 8:keyname = "[backspace]"; break;  case 9:keyname = "[Tabulation]"; break;  Case 13:keyname = "[Enter]"; break;  Case 32:keyname = "[Space]"; break;  Case 33:keyname = "[PageUp]"; break;  Case 34:keyname = "[PageDown]";     break;   Case 35:keyname = "[end]"; break;  Case 36:keyname = "[Home]"; break;  Case 37:keyname = "[Direction key left]"; break;  Case 38:keyname = "[Direction key on]"; break;  Case 39:keyname = "[Direction key right]"; break;  Case 40:keyname = "[Direction key]"; break;  Case 46:keyname = "[Delete]"; break;  default:keyname = ""; break; }  keystring = keyname; }  $ ("content") .innerhtml=keystring; }  Ion KeyUp (E)   {  $ ("content") .innerhtml=keystring; }  document.onkeypress=keypress;  Document.onkeydown =keydown;  document.onkeyup =keyup;  </script>  <input type= "text"/>   <input type= "button" value= "Empty Record" onclick= "$ (' content '). InnerHTML = '; keystring = '; />  <br/> Please press any key to view the keyboard response key value: <span id= "Content" ></span>  </BODY>  </html >    Code Analysis:  $ (): Get dom    KeyPress (e) According to ID: Implement the Intercept of character code, because the function key is to use KeydOwn, so the buttons are blocked in the keypress.     KeyDown (E): mainly to achieve the function of the key to obtain.     KeyUp (E): Displays the intercepted string.
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.