An important aspect of JavaScript events is that they have some relatively consistent features that can provide powerful functionality for development.
The most convenient and powerful is the event object, they can help you handle mouse events and keyboard percussion aspects of the situation;
In addition, you can modify the function of the capture/bubbling flow of a general event;
An Event object
One of the standard attributes of an event-handling function is that the event object accessed in some way contains contextual information about the current event;
Event handling consists of three parts: object. event handler function = function;
Document.onclick = function () {
alert (' Lee ');
}
PS: The above procedure explanation: Click indicates an event type, clicks;
OnClick: an attribute (or event listener) representing an event-handling function or bound object;
Document: Represents a bound object that triggers an element region;
function (): Anonymous functions are executed functions that are used to trigger execution;
In addition to using the method of anonymous function as a function to be executed, can also be set into a separate function;
Document.onclick = box; Direct assignment function name can be, without parentheses;
function box () {
alert (' Lee ');
}
This keyword and context
//In the Object-oriented chapter we learned that in an object, because of the scope of the relationship, this represents the nearest object;
var input = document.getelementsbytagname (' input ') [0];
Input.onclick = function () {
alert (this.value); Htmlinputelement,this represents the input object;
}
When an event is triggered, an event object is generated that contains all the information related to the event;
Includes the type of element/event that causes the event/and other information related to a particular event;
Event object, which we generally refer to as an event object, is passed by the browser as a parameter through a function;
First of all, we have to verify that there are no parameters passed in the executive function, whether the hidden parameters can be obtained;
function box () { //ordinary null parameter functions;
alert (arguments.length); 0; No parameters to be passed;
}
Input.onclick = function () { //event binding execution;
alert (arguments.length); 1; get a hidden parameter;
}
PS: Through the above two sets of functions, we found that the execution function by event binding can get a hidden parameter;
Description, the browser will automatically assign a parameter, this parameter is actually an event object;
Input.onclick = function () {
alert (arguments[0]); MouseEvent, mouse event object;
}
The above approach is more troublesome, so the simpler approach is, directly through the receiving parameters to get;
Input.onclick = function (evt) { //Accept Event object,
alert (evt); MouseEvent, mouse event object;
}
Directly receive the event object, is the practice of the consortium, IE does not support, ie himself defined an event object, directly in the window.event access;
Input.onclick = function (evt) {
var e = evt | | window.event;
Alert (e); Implements CROSS-BROWSER-compatible fetch event objects;
Through the event object can get to the mouse button information and screen coordinate acquisition, etc.
Two mouse events
//mouse events are the most commonly used in the web above a class of events, after all, the mouse is still the most important positioning equipment;
1. mouse button
The Click event is triggered only when the primary mouse button is clicked (typically the left mouse buttons), so the information for the detection button is not necessary;
However, for the MouseDown and MouseUp events, there is a button property in its event object that indicates that the press or Release buttons are pressed;
The Button property value in non IE (Universal) indicates that 0 is the primary mouse button (usually the left button).
1 indicates the middle mouse button (mouse wheel button);
2 for The second mouse button (generally the right button);
The button attribute 1 in
ie indicates the primary mouse button (usually the left button);
2 for The second mouse button (generally the right button);
4 indicates that the middle mouse button is pressed;
mouse button compatible;
function Getbutton (evt) {
var e = evt | | window.event;
if (evt) { //Chrome browser supports both the consortium and IE standards;
return E.button; Pay attention to the order of judgment;
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 (' Press the left mouse button! ')
else if (Getbutton (evt) = = 1) {
alert (' Pressing the middle key ');
} else if (Getbutton (evt) = = 2) {
alert (' Press the right button! ');
}
2. Visual area and screen coordinates
The event object provides two sets of properties to obtain the browser coordinates://A group is the page visual area coordinates;
A set of screen coordinates;
The coordinate attribute property describes the ClientX visual region x coordinate, the distance from the left border;
ClientY the visual area y-coordinate, distance from the top border;
ScreenX screen Area x coordinates, distance from the left screen;
ScreenY Screen Area y-coordinate, distance from the screen;
Pagex The X coordinate of the page, the distance from the left frame of the whole page;
Pagey the y-coordinate of the page, the distance from the top border of the page;
To judge the mouse click position function;
Document.onclick = function (evt) {var e = evt | | window.event;
Alert (e.clientx+ ', ' +e.clienty);
Alert (e.screenx+ ', ' +e.screeny);
Alert (e.pagex+ ', ' +e.pagey);
}//PS: The values of Pagex and pagey are equal to the values of Clientx and clienty when the page does not scroll;
IE8 The following does not support page coordinates on event objects, but can be computed using client area coordinates and scrolling information;
The ScrollTop and ScrollLeft properties in the Document.body (promiscuous mode) or document.documentelement (standard mode) are needed at this time;
Pagex and Pagey compatible functions;
var div = document.getElementById (' mydiv ');
AddEventListener (Div, ' click ', Function (evt) {var evt = event | | window.event;
var Pagex = Evt.pagex, pagey = Evt.pagey;
if (Pagex = = undefined) {Pagex = evt.clientx+ (Docuemnt.body.scrollLeft | | document.documentElement.scrollLeft); } if (Pagey = = UNdefined) {Pagey = evt.clienty+ (Document.body.scrollTop | | document.documentElement.srollTop);
alert (Pagex+pagey); });
3. Modify Key
Sometimes, we need to use some keys on the keyboard to match the mouse to trigger some special events;
These keys are: shift/ctrl/alt and meat (window is Windows key, Apple machine is the CMD key);
They are often used to modify mouse events and behavior, so called modifier keys;
Modify the Key Property
Property description
Shiftkey Determines whether the SHIFT key is pressed;
Ctrlkey to determine whether to press the Ctrlkey key;
Altkey to determine whether the ALT key was pressed;
Metakey to determine whether to press the Windows key, IE does not support;
To judge the key function;
function Getkey (evt) {
var e = evt | | window.event;
var keys = [];
if (E.shiftkey) keys.push (' shift '); Determines whether the SHIFT key is pressed at the same time;
if (E.ctrlkey) keys.push (' Ctrl ');
if (E.altkey) Keys.push (' Alt ');
return keys;
}
Document.onclick = function (evt) {
alert (Getkey (EVT)); Gets an array that may contain shift/ctrl/alt values;
}
Three keyboard events
Keyboard events are triggered when users use the keyboard;
"DOM2-level event" initially specified the keyboard event, and then deleted the corresponding content;
Ultimately, the initial keyboard event was used, but IE9 was the first to support the "DOM3" level keyboard event;
1. Key code
When the KeyDown and KeyUp events occur, the KeyCode property of the event object contains a code that corresponds to a specific key on the keyboard;
For the alphanumeric character set, the value of the KeyCode property is the same as that of the lowercase letter or number in the ASCII code; the capitalization of the letter does not affect;
Document.onkeydown = function (evt) {
alert (evt.keycode);
}
2. Character encoding
The event object of Firefox/chrome/safari supports a charcode attribute;
This property contains a value only if the KeyPress event occurs, and this value is the ASII encoding of the character that the key is pressed on; (also includes a key other than numbers and letters);
At this time the keycode is usually equal to 0 or may be equal to the key code;
IE and opear the ASCII encoding of the characters in the KeyCode;
function Getcharcode (evt) {
var e = evt | | window.event;
if (typeof E.charcode = = ' number ') {return
e.charcode;
} else{return
E.keycode
}
}
document.onkeypress = function (evt) {
alert (Getcharcode (EVT));
}
PS: You can use String.fromCharCode () to convert the ASCII encoding to the actual character;
Four and IE
//In standard DOM events, the event object contains properties and methods related to the specific event in which it was created;
The event types that are triggered are not the same, and the available properties and methods are different;
properties and methods of event objects in the Consortium
Property/method Type read/write description
Bubbles Boolean Read-only indicates whether the event is bubbling;
Cancelable Boolean Read-only indicates whether the default behavior of the event can be canceled;
The Currenttarget element reads only those elements whose event handlers are currently handling the event;
Detail Integer read-only details related to the event (generally used for the value of the wheel information);
Eventphase Integer read-only call event handler stage: 1 for capture phase, 2 for processing target, 3 for bubbling phase;
Preventdefault () Function is read-only to cancel the default behavior of the event; if the value of cancelable is true, you can use this method;
The Stoppropagation () Function is read-only to cancel further capture or bubbling of the event, or to use this method if the bubbles value is true;
Target Element read-only event;
Type String reads only the types of events that are triggered;
View Abstractview only the abstract view associated with the event, which is equivalent to the Window object where the event occurred;
properties of the event object in IE
Attribute type read/write description
The cancelbubble Boolean read-write default value is false, but setting it to true can cancel event bubbling;
ReturnValue Boolean Read-write default is true, but setting its value to False can cancel the default behavior of the event;
Target of Srcelement Element read-only event;
Type String reads only the event types that are triggered;
Compatible target and srcelement functions function
gettarget (evt) {
var e = evt | | window.event;
return E.target | | e.srcelement; Get the event target DOM object compatible
;
Document.onclick = function (evt) {
var target = Gettarget (evt);
alert (target);
}
Five Event Flow
An event flow is a description of the order in which the events are received from the page, and when several elements with events cascade together, click on one of the elements;
It is not only the currently clicked element that triggers the event, but all the elements that cascade across the range of clicks will trigger the event;
The event flow consists of two modes: bubbling and capturing;
1. Event bubbling
is triggered from inside to outside;
2. Event Capture
is triggered from the outside to the inside;
Modern browsers are all bubble types; Capture mode is the early Netscape default;
Now the browser to use the DOM2-level model of the event binding mechanism to manually define the event flow pattern;
Document.onclick = function () {
alert (' I am Document ');
}
Document.documentElement.onclick = function () {
alert (' I am html ');
}
Document.body.onclick = function () {
alert (' I am body ');
}
document.getElementById (' box '). onclick = function () {
alert (' I am div ');
}
document.getElementsByTagName (' input ') [0].onclick=function () {
alert (' I am input ');
}
PS: Click Input will be bubbling to the document gradually;
Block event bubbling compatible functions function
Stoppro (evt) {
var e = evt | | window.event;
If there is a cancelbubble, IE browser, set its value to true to prevent event bubbling;
Otherwise, the blocking event bubbling method in the stoppropagation () is executed.
Window.event? e.cancelbubble = True:e.stoppropagation ();
}