Compatible with IE and Firefox Firefox's return event (JS and jquery) _javascript tips

Source: Internet
Author: User
Tags delete key key string numeric value printable characters
JavaScript compatible with IE and Firefox Firefox's carriage return event
Copy Code code as follows:

<script language= "JavaScript" >
function KeyPress (e)
{
var currkey=0,e=e| | Event
if (e.keycode==13) document.myform.submit ();
}
document.onkeypress=keypress;
</script>


Copy Code code as follows:

<script>
Document.onkeydown=function (Event)
{
E = event? Event:(window.event? Window.event:null);
if (e.keycode==13) {
Methods of execution
Alert (' Carriage return detected ');
}
}
</script>


jquery compatible with IE and Firefox Firefox's carriage return event
Copy Code code as follows:

$ (document). Ready (function () {
$ ("Press Enter Control"). KeyDown (function (e) {
var curkey = E.which;
if (Curkey = = 13) {
$ ("#回车事件按钮控件"). Click ();
return false;
}
});
});

jquery Multi-browser capture carriage return event code
Copy Code code as follows:

$ (document). KeyDown (function (event) {
if (Event.keycode = = 13) {
$ (' form '). each (function () {
The code that you want to run
});
}
});


jquery-based button default Enter event (carriage return event)
Here, let me introduce the button to the default carriage return (enter) event. If you can use submit, you do not need to look at the following code, because submit can be directly the default carriage return event (enter)
Hereby declare that the code is done through jquery. The actual column code I wrote personally, can be implemented completely, as long as the copy used, but must import jquery package. A way to support IE and Firefox, absolutely. When I was doing it, I found some code on the Internet, which basically didn't support Firefox. Well, that's a lot of nonsense. Start the Code demo. Welcome everyone to pick the wrong, and technical advice, thank you.
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//w< xmlnamespace prefix =" ST1 "ns =" Urn:schemas-microsoft-com:office:smarttags "/>3c//dtd XHTML 1.0 transitional//en "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<title> Firefox and IE both support the Enter event </title>
<script src= "Jquery.1.3.2.js" type= "Text/javascript" language= "JavaScript" ></script>
<script type= "Text/javascript" >
Document.onkeydown = function (e) {
var theevent = window.event | | E
var code = Theevent.keycode | | Theevent.which;
if (code = = 13) {
$ ("#but1"). Click ();
}
}
$ (document). Ready (function () {
$ ("#but1"). Click (function () {
Alert ("I am the Enter event," + "text value:" + $ ("#text1"). Val ());
})
$ ("#but2"). Click (function () {
Alert ("I am jquery event" + "Text value:" + $ ("#text1"). Val ());
})
});
</script>

This problem is solved, if there is a better solution also want to come out and share.

Today do a return key to submit the form login function, my code is as follows:
Copy Code code as follows:

<script language= "JavaScript" >
function document.onkeypress ()
{
if (event.keycode==13) document.myloginform.submit ();
}
</script>

A mistake was made when executing in Firefox: missing (before formal parameters

According to the suggestion of the Internet, I changed my source code again:
Copy Code code as follows:

<script language= "JavaScript" >
Document.onkeypress=function ()
{
if (event.keycode==13) document.myloginform.submit ();
}
</script>

An error is also obtained for an event is not defined.

Looking for, I found it (as follows):
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 – generally, 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

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
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.

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 ...

According to its pointers, I modified my code to:
Copy Code code as follows:

<script language= "JavaScript" >
function KeyPress (e)
{
var currkey=0,e=e| | Event
if (e.keycode==13) document.myform.submit ();
}
document.onkeypress=keypress;
</script>

Success!

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.