JavaScript key events (compatible with each browser) _javascript tips

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

Part I: Key events in the browser

Use JS to implement keyboard records, to pay attention to the browser's three key event types, that is, keydown,keypress and KeyUp, they correspond to the onkeydown, onkeypress and onkeyup These three event handles respectively. A typical button will produce all three events, followed by Keydown,keypress, and then the KeyUp when the button is released.

Of 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]

However, KeyPress can only be valid for some characters that can be printed, and for function keys, such as F1-F12, Backspace, Enter, Escape, PageUP, PageDown, and arrow directions, there is no KeyPress event. However, KeyDown and KeyUp events can be generated. 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 Two: compatible browsers

Any 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 Initialization of the event

The first thing you need to know is how to initialize the event, the basic statement is as follows:

function KeyDown () {}
Document.onkeydown = KeyDown;

When the browser reads this statement, the KeyDown () function is called regardless of which key is pressed on the keyboard.

2.2 Firefox and Opera's implementation method

Firefox and Opera and other programs to achieve more 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)

The variable e indicates that a keystroke event occurs to find which key is being pressed, and to use the which attribute:

E.which

E.which will give the index value of the key, the method of converting 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 to be pressed which is the key:

Copy Code code as follows:

function KeyDown (e) {
var keycode = E.which;
var Realkey = String.fromCharCode (E.which);
Alert ("Key code:" + KeyCode + "character:" + Realkey);
}
Document.onkeydown = KeyDown;

the realization method of 2.3 ie

IE program does not need e variable, use Window.event.keyCode to replace E.which, the key index value into the real key method similar: String.fromCharCode (Event.keycode), the program is as follows:

Copy Code code as follows:

function KeyDown () {
var keycode = Event.keycode;
var Realkey = String.fromCharCode (Event.keycode);
Alert ("Key code:" + KeyCode + "character:" + Realkey);
}
Document.onkeydown = KeyDown;

2.4 Determining browser type

Above understand in a variety of browsers is how to achieve the key event object method, then need to judge the browser type, this method many, there are more convenient to understand, there are very clever way to first say the general method: is to use the Navigator object appname properties, Of course, you can use the UserAgent attribute, where you use appname to determine the browser type, IE and Maxthon appname are "Microsoft Internet Explorer," and Firefox and opera appname are " Netscape ", so a simpler code for the function is as follows:

Copy Code code as follows:

function KeyUp (e) {
if (navigator.appname = = "Microsoft Internet Explorer")
{
var keycode = Event.keycode;
var Realkey = String.fromCharCode (Event.keycode);
}else
{
var keycode = E.which;
var Realkey = String.fromCharCode (E.which);
}
Alert ("Key code:" + KeyCode + "character:" + Realkey);
}
Document.onkeyup = keyUp;

The simpler approach is [2]:
Copy Code 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;

The above method is more ingenious, the simple explanation:
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 the browser, 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

Key code and character code for 3.1 key events

button code and character code for key events lack portability between browsers, and for different browsers and different case events, key and character codes 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 codes, which, in keypress time, 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 the function key, and the KeyPress event is most useful for the printable key [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 Implementation of the Code
The general idea, with KeyPress event object to get the key characters, using KeyDown event to get functional characters, such as Enter,backspace.

The code implementation is shown below

Copy Code code as follows:

! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<meta name= "generator" content= "EditPlus" >
<meta name= "Author" content= "feather War ren" >
<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)
{
Block backspace, tabulation, carriage return, space, direction key, delete key
Case 8:case 9:case 13:case 32:case 37:case 38:case 39:case 40:case 46:keyname = "";
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;
}
function 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/> Press any key to view the keyboard response key value: <span id= "Content" ></span>
</BODY>
</HTML>

Code Analysis:
$ (): Get DOM from ID

KeyPress (E): To achieve the interception of character code, because the function keys to use KeyDown to obtain, so in the KeyPress screen these function keys.

KeyDown (E): mainly to achieve the function of the key to obtain.

KeyUp (E): Displays the intercepted string.

Related Article

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.