JS Keyboard record implementation (compatible with Firefox and IE) _javascript skills

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

Mainly divided into four parts
Part I: Key events in the browser
Part Two: compatible browsers
Part III: Code implementation and optimization
Part IV: summary

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:

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:

function KeyDown () {
var keycode = event.keycode;
var realkey = String.fromCharCode (Event.keycode);
alert (" Key code:" + KeyCode + "character:" + R  Ealkey);
    } 
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:

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); 11>
}
alert ( "key code:" + KeyCode + "character:" + realkey );
}
Document.onkeyup = keyUp;

The simpler approach is [2]:

function KeyUp (e) {
  var currkey=0,e=e| | Event
                 currkey=e.keycode| | e.which| | E.charcode;
            var KeyName = String.fromCharCode (Currkey);
                                     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

Key event key code and character code lack of portability between browsers, for different browsers and different case events, key code and character code storage mode are different, key events, browser and key event object properties of the relationship between the following table:

As shown in the table:

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

! 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 = "";   & nbsp    break;
    &NBSP;}
     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.

The code basically even completes! Oh

Part IV: summary

The original purpose of writing code is to be able to record keystrokes through JS and return a string.

The above code is only using JS to achieve the basic English key record, for Chinese characters is powerless to record Chinese characters, I can think of the way, of course, with JS, is using KeyDown and KeyUp record the underlying key events, Chinese character parsing of course powerless. Of course, you can use DOM to directly access the Chinese characters in the input, but this has left the text discussed in this article with key events to achieve the original key record.

The above code can also implement the function of adding a clipboard, monitoring the function of deletion and so on ...

Reference:

[1] Fifth edition of the JavaScript Authority guide O ' REILLY press/Machinery Industry Press 424 Page
[2] Fifth edition of the JavaScript Authority guide O ' REILLY press/Machinery Industry Press 427 Page
[3] Fifth edition of the JavaScript Authority guide O ' REILLY press/Machinery Industry Press 425 page

Appendix:

Key list of keys for commonly used key codes:

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.