Object for JavaScript events

Source: Internet
Author: User
Tags modifier



Object of the event

An important aspect of JavaScript events is that they have some relatively consistent characteristics that can provide more powerful capabilities for our development. The most convenient and powerful is the event object, they can help you deal with the mouse and keyboard aspects of a lot of things, in addition, we can also modify the general event of the capture or bubbling stream function.

1. Event Object

A standard feature of an event handler is that an event object that is accessed in some way contains contextual information about the current event.

Event handling consists of three parts: an object. The event handler function = function. For example, click anywhere in the document.

In addition to using anonymous functions as functions that are executed, you can also set them as separate functions.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >//eg: Click anywhere in the document Document.onclick = function () {    alert (this),//htmldocument, delegate is document}; window.onload = function () {    Document.onclick = box;//because the box () function has been bound by the onclick, so the inside of this represents the document};    Box ();//object window, if you call box () at the global scope, this represents the Window function box () {alert (this) and//htmldocument, which represents the document}</ Span>

When an event is triggered, an event object is generated that contains all the information related to the event. Includes the element that caused the event, the type of the event, and other information related to the specific event.

Event object, which we generally call an event object, is a browser that passes the object as a parameter through a function. So first, we have to verify that there are no arguments passed in the execution function, and that the hidden arguments can be obtained.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >//whether a hidden parameter can be obtained. function box () {        alert (arguments.length);//Get the number of parameters: 0} box (); document.onclick = function () {  //Get the number of parameters: 1     alert (arguments.length);//If the function is bound by the event handler, the browser will pass a parameter by default, which is the event object     alert (Arguments[0]);//mouseevent, Mouse Event Object};</span>


This keyword and context
An execution function that is bound by an event can have a hidden argument. Note that the browser automatically assigns a parameter, which is actually the event object.

Simple procedure, directly by receiving parameters to get

Directly receive the event object, is the practice of the Internet, IE does not support, IE itself defines an event object, directly in the window.event to get.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >//eg: Event compatible ie browser    window.onload = function () {            document.onclick=function (evt) {            var e = evt | | window.event;   Online | | IE            alert (e);        };    //ps:window.event This property IE is supported, Chrome is also supported,//ps:chrome is also supporting the//PS: if both the Internet and IE support, Then we have the </span>
<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ></span>
<pre class= "html" name= "code" ><span style= "font-family:simsun;font-size:18px;" >//Cross-browser left-right-click Response function Getbutton (evt) {    var e = evt| | window.event;    if (evt) {        return e.button;    } else if (window.event) {        switch (e.button) {case            1:                return 0;            Case 4:                return 1;            Case 2:                return 2;}}    } Document.onmouseup=function (evt) {    if (Getbutton (evt) ==0) {        alert ("You press Left button!");    } else if (Getbutton (evt) ==1) {        alert ("You press Midle button!");    } else if (Getbutton (evt) ==2) {        alert ("You press Right button!");    }; </span>

2. Mouse Events

Mouse events are the most common type of event on the web, after all, the mouse is still the most important positioning device. Then through the event object can get to the mouse button information and screen coordinate acquisition and so on.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >//gets the coordinates of the visual area and screen Area window.onload = function () {    document.onclick=function (evt) {        var e = evt | | window.event;   Online | | IE        alert (e.clientx+ ', ' +e.clienty+ ', ' +e.screenx+ ', ' +e.screeny ');};    </span>


The Click event is triggered only when the primary mouse button is clicked (usually the left button of the mouse), so it is not necessary to detect the button's information. For MouseDown and MouseUp events, however, there is a button property in their event object that represents the press or Release button.


Button properties in non-IE (Internet Explorer)




the button property in IE


In the vast majority of cases, we only use the primary and secondary three click Key, ie given the other key combinations are generally not available. So, we just need to do these three kinds of compatibility can.

<pre class= "html" name= "code" ><span style= "font-family:simsun;font-size:18px;" >//Cross-browser left-right-click Response function Getbutton (evt) {    var e = evt| | window.event;    if (evt) {        return e.button;    } else if (window.event) {        switch (e.button) {case            1:                return 0;            Case 4:                return 1;            Case 2:                return 2;}}    } Document.onmouseup=function (evt) {    if (Getbutton (evt) ==0) {        alert ("You press Left button!");    } else if (Getbutton (evt) ==1) {        alert ("You press Midle button!");    } else if (Getbutton (evt) ==2) {        alert ("You press Right button!");    }; </span><span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ></span>

2. Visual area and screen coordinates event objects provide two sets of properties for the browser coordinates, one for the left side of the page visibility and the other for screen coordinates. Coordinate properties

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >//gets the coordinates of the visual area and screen Area window.onload = function () {    document.onclick=function (evt) {        var e = evt | | window.event;   Online | | IE        alert (e.clientx+ ', ' +e.clienty+ ', ' +e.screenx+ ', ' +e.screeny ');};    </span>


3. Modifier keys
Sometimes, we need to use some keys on the keyboard to match the mouse to trigger some special events. These keys are: Shfit, Ctrl, Alt, and meat (Windows keys in Windows, cmd in Mac), which are often used to modify mouse events and behavior, so they are called modifier keys.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >//Double-click the modifier key--Hold down SHIFT and double-click window.onload = function () {    Document.ondblclick = function (evt) {        alert (GetKey (evt ));    };}; function GetKey (evt) {    var e = evt | | window.event;    var keys = [];    if (E.shiftkey) keys.push (' shift ');    if (E.ctrlkey) keys.push (' Ctrl ');    if (E.altkey) Keys.push (' Alt ');//Click the shortcut key for +alt and 360 to conflict with    return keys;} </span>

3. Modifier keys
Modifying key properties


Keyboard events

The keyboard event is triggered when the user is using the keyboard. The "DOM2 level event" initially defined the keyboard event, and the result was deleted. The initial keyboard event is still used, but IE9 has been the first to support "DOM3"-level keyboard events.

1. Key code
Different browsers in the KeyDown and KeyUp events, there are some special cases.
In Firefox and Opera, the semicolon key has a keycode value of 59, which is the encoding of semicolons in ASCII, while IE and Safari return 186, which is the key code for keys in the keyboard.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >//keydown, press any key, press the meaning is to press the immediate trigger//keyup, is to play any key, bounce is to press and then release Trigger//keypress, is to press the character key, abc,123, special characters ah what. Shift,ctrl,alt and so on is not the key of the character invalid//key: Any key on the keyboard,//character encoding: Keyboard can output characters of the key//key code returned is the ASCII lowercase letter corresponding to the key code just return the value of that key, do not recognize the letter case// The key code is consistent on the character and ASCII of the character encoding.        The key code can return the encoding of any key, and the letter is not case sensitive//key code is seemingly compatible in all browsers Document.onkeydown = function (evt) {var e = evt | | window.event; alert (e.keycode);//keycode return key code alert (E.charcode);//charcode return key}; If you return to KeyCode with KeyPress, the Firefox browser will return all character keys 0,//chrome support keypress return keycode, but also support case//ie support KeyPress return keycode, and also support the case//different browser on; number on the return key value inconsistent, if used, need to do compatible//charcode in the case of using KeyPress, Firefox will return the character pad encoding, support case// IE and opera do not support charcode this attribute//Generally, we do not care about the character key, basically processing is the characters button, so document.onkeypress = function (evt) {alert (String.fromchar Code (Getcharcode (EVT)));//charcode return character encoding};    All browsers support character key function Getcharcode (evt) {var e = evt | | window.event;    if (typeof E.charcode = = ' number ') {return e.charcode; } else {        return e.keycode;     }}//character encoding each browser detects document.onkeypress = function (evt) {var e = evt | | window.event; alert (e.keycode);//keycode return key code alert (E.charcode);//charcode return key};</span>

2. Character encoding
The event objects for Firefox, Chrome, and Safari all support a CharCode property that contains the value only when the KeyPress event occurs, and that the value is the ASCII encoding of the character represented by the pressed key. At this point the keycode is usually equal to 0 or it may be equal to the key code. IE and opera are ASCII-encoded characters that are stored in keycode.

You can use String.fromCharCode () to convert an ASCII encoding into an actual character.

The differences between KeyCode and CharCode are as follows: When you press the "a" key (which is the lowercase letter).

Keydown:keycode is 65  CharCode is 0
KeyUp:    keycode are charcode is 0
Keypress:keycode are 0  charcode is +

in IE You get the
Keydown:keycode is 65  charcode are undefined
keyup:      keycode is 65  CharCode is undefined
keypress:  keycode are 97  charcode is undefined

And when you press the SHIFT key, you get the
Keydown:keycode is 16  charcode in Firefox is 0
keyup:      KeyCode is 16   charcode is 0

In IE, you will get
Keydown:keycode is charcode undefined
Keyup:keycode is charcode undefined

KeyPress: No charcode value is obtained because pressing SHIFT does not enter any characters and does not trigger the KeyPress transaction.
Within the KeyDown transaction, the transaction contains the physical encoding of the keys pressed by the keycode– user.

In KeyPress, KeyCode contains the character encoding, the ASCII code of the implied character. This situation is useful for all browsers – in addition to Firefox, its keycode return value in KeyPress transactions is 0.


the with the IE

In a standard DOM event, the event object contains properties and methods related to the specific event that created it. The types of events that are triggered are different, and the available properties and methods are different.

Properties and methods of event objects in the audience



? properties of the event object in IE

Here, we only look at properties or methods that are compatible with all browsers. First of all, let's look at the target in the srcelement and the Internet Explorer, both of which represent the goal of the event.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >//Where you click, you can get where the DOM element object function Gettarget (evt) {    var e = evt | | window.event;    return E.target | | E.srcelement; }  Document.onclick = function (evt) {    alert (Gettarget (EVT));}; </span>


Event Flow
The event flow is a description of the order in which events are accepted from the page, and when several elements with events cascade together, then you click on one of the elements, not only the currently clicked element will trigger the event, but all the elements stacked in your click range will trigger the event.
The event flow consists of two modes: bubbling and capturing.


Event bubbling is triggered from inside to outside.
Event captures are triggered from the outside to the inside.

modern browsers are bubbling models by default, while capture mode is the default for early Netscape. Today's browsers use the event-binding mechanism of the DOM2-level model to manually define the event flow pattern.

in the process of blocking bubbles, the different methods used by the Internet and IE, we have to do a little bit of compatibility.
<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >//Event Flow bubbling Event Window.onload = function () {    Document.onclick = function () {        alert (' document ');    };    Document.documentElement.onclick = function () {        alert (' HTML ');    };    Document.body.onclick = function () {        alert (' body ');    };    document.getElementById (' box '). onclick = function () {        alert (' div ');    };    document.getElementsByTagName (' input ') [0].onclick = function (evt) {        var e = evt | | window.event;        Alert (' input ');        E.stoppropagation ();//w3c Cancel bubbling        //alert (e.cancelbubble);        e.cancelbubble = true;//ie de        -bubbling setstop (e);        Cancel bubbling compatible with all browsers    };    function Setstop (e) {        (typeof e.stoppropagation = = ' function ')? E.stoppropagation (): E.cancelbubble = true;    } };</span>

As for the learning of events, and in the process of further deepening, the understanding of event objects makes me more fully aware of events, and also lays the foundation for my flexible use of events.




Object for JavaScript events

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.