Home >Web Front-end >JS Tutorial >Understanding events in JavaScript_javascript tips

Understanding events in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 19:25:541074browse

In many language learning, "event" is a difficult concept to understand, but it is also a very important concept. The same is true for event processing in javascript. It is precisely because of event processing that the Ajax drag effect occurs. This article discusses event handling in JavaScript. After reading it, you will know how many Ajax frameworks implement dragging effects.
1. IE Event Object
(1) Main properties and methods of IE Event Object
In IE, there is an object called Event that is specifically responsible for event processing. This object is responsible for event processing and contains many attributes. and methods. By calling these methods and attributes, a lot of event processing can be completed.
Type: The type of event, which is the string after the "on" prefix in the HTML tag attribute. For example, "Click" represents a click event.
srcElement: The event source is the element where the event occurs.
Button: declares the pressed mouse button, which is an integer. 1 represents the left mouse button, 2 represents the right mouse button, and 4 represents the middle mouse button. If multiple mouse buttons are pressed, these values ​​are added together, so 3 represents the left and right buttons pressed at the same time.
ClientX/clientY: refers to the horizontal and vertical coordinates of the mouse when the event occurs. Integers are returned, and their values ​​are generated relative to the upper left corner of the containing window.
OffsetX/offsetY: The position of the mouse pointer relative to the source element can determine which pixel of the Image object is clicked.
 altKey, ctrlKey, shiftKey: As the name suggests, these properties refer to whether the Alt, Ctrl or Shift keys are pressed at the same time when the mouse event occurs, and a Boolean value is returned.
KeyCode: Returns the key code when the keydown and keyup events occur, and the Unicode character of the keypress event.
 fromElement and toElement. The former refers to the document element moved by the mouseover event, and the latter refers to the document element moved by the mouse in the mouseout event.
CancelBubble: A Boolean attribute. When it is set to true, the stop event will be further bubbled to the containing level element.
ReturnValue: A Boolean attribute. When set to false, it can organize the browser to perform default event actions, equivalent to .
AttachEvent() and detachEvent() methods: methods to register multiple event processing functions for specifying DOM object event types. They have two parameters, the first is the event type, and the second is the event processing function. When the attachEvent() event is executed, the this keyword points to the window object, not the element where the event occurred.
(2) Some explanations of the IE Event object
1. The IE Event object is a global property
In IE, the Event object cannot be passed as a parameter to the event handler. You can only use window.event or event to reference the Event object. Because in IE, Event is a property of window, which means event is a global variable. This variable provides the details of the event.
2. Bubbling of events in IE: Events in IE can bubble up to the upper layer bit by bit along the containment level. That is to say, the event processing function defined by the DOM node in the lower layer will reach the node in the upper layer. If the event handler function is of the same event type, the upper event handler function will also be executed. For example, the

tag contains , and if both tags have onclick event handlers, the execution will be to execute the onclick event handler of the tag first, and then execute the to be executed after the event processing function of is completed, then set cancelBubble to false.
 
2. Example of dragging DOM elements in IE

Copy the code The code is as follows:

/*
This function is called by the mousedown event handler
It registers temporary capture event handlers for subsequent mousemove and mouseup events
and uses these event handlers to drag the specified Document element
The second parameter must be the event object of the mousedown event
*/
function beginDrag(elementToDrag,event)
{
//Where the element is currently located
/ /The style properties of this element must have left and top CSS attributes
//In addition, we assume that they are in pixels
//var x=parseInt(elementToDrag.style.left);
// var y=parseInt(elementToDrag.style.top);

//Calculate the distance between a point and the mouse click. The nested moveHandler function below requires these values
var deltaX=event.clientX -parseInt(elementToDrag.style.left);
var deltaY=event.clientY-parseInt(elementToDrag.style.top);

// Handlers for mousemove and mouseup events that occur after registering the mousedown event
// Note that they are registered as capture event handlers for the document
// These event handlers remain active while the mouse button remains pressed
// When the button is released when they are deleted
document.attachEvent("onmousemove",moveHandler);
document.attachEvent("onmouseup",upHandler);

//We have already handled the event, don’t Let other elements see it
event.cancelBubble=true;
event.returnValue=false;

/*
This is the handler that captures the mousemove event when the element is dragged , which responds to the moving element

*/
function moveHandler(e)
{
//Move the element to the current mouse position
e=window.event;
elementToDrag.style.left=(event.clientX-deltaX) "px";
elementToDrag.style.top=(event.clientY-deltaY) "px";

//Don’t let anything else The element sees this event
event.cancelBubble=true;
}

/*
This event will capture the mouseup event that occurs when the drag ends
*/
function upHandler(e)
{
//Unregister event handler
document.detachEvent("onmouseup",upHandler);
document.detachEvent("onmousemove",moveHandler);}

event.cancelBubble=true;
}
Call its HTML file code:


Untitled Page

 


 

Drag me


 

This is a test.Testing,testing



3. Advanced event processing in DOM
The event processing in IE 6 is not the W3C DOM standard event processing model, so if the above code is run in the Mozilla Firefox browser, it will lose its effect. The upcoming IE 7 will also support the W3C DOM secondary standard, so it is very important to master the advanced event processing of DOM, because the W3C DOM secondary standard is the future development direction of the Web, and the W3C DOM API is very commonly used. Provides a good foundation for more complex web development in the future.
(1) Scope of event handlers and event propagation
Before formally discussing DOM advanced event processing, we need to understand the scope of event handlers. The scope of an event handler is much more complex than an ordinary function scope. Ordinary function scope chains are relatively easy. For example, if you want to find a variable a in an ordinary function, the JavaScript interpreter will first check whether there is a variable a in the calling object of the function. If not, it will be found in the scope chain. The next object is usually searched in the global object. But event handlers are not that simple, especially when defined with HTML attributes. The head of their scope chain is the object that calls them, and the next object is not the global object, but the object that triggers the event handler. This will cause a problem. Both window and document have a method open(). If open() is not modified before, then the document.open() method will be called in the event processing function instead of the commonly used window. open() method, so when using it, it should be clearly specified as window.open().
(2) Event propagation and registered event handler
1. Event propagation
In the secondary DOM standard, the event handler is more complicated. When an event occurs, the event handler of the target node will is triggered to execute, but the parent node of the target node also has the opportunity to handle this event. The propagation of events is divided into three stages. The first is the capture stage. The event is propagated from the Document object down the DOM tree to the target node. If any parent node of the target has registered a handler for capturing the event, the event will be propagated during the propagation process. This program will be run first. The next stage occurs on the target node itself, and the corresponding event handler registered on the target node will be executed; the last stage is the bubbling stage, where the event will be uploaded back to the parent node from the target node. Similarly, if the parent node has The corresponding event handler will also handle it. In IE, there is no capturing phase, but there is a bubbling phase. You can use the stopPropagating() method to stop event propagation, that is, to make other elements invisible to this event. In IE 6, set cancelBubble to true.
2. Register event handler
Like IE, the DOM standard also has its own event handler, but the event handler of the DOM secondary standard is more powerful than IE. The event handler is registered using the addEventListner method. The method has three parameters. The first is the event type, the second is the processing function, and the third is a Boolean value. true means that the specified event handler will be used to capture the event during the event propagation stage, otherwise it will not be captured. , the function that executes this event processing is triggered when an event occurs on the object, or when it occurs on a byte point of the object and bubbles up to the object, the function that executes this event processing is triggered. For example: document.addEventListener("mousemove", moveHandler, true); is to call the moveHandler function when the mousemove event occurs and can capture the event.
You can use addEventListener to register multiple event handlers for an event, but the execution order of these functions is uncertain and is not executed in the order of registration like C#.
When registering an event handler with addEventListener in Mozilla Firefox, the this keyword represents the document element that calls the event handler. However, this is not necessarily the case in other browsers because this is not a DOM standard. The correct approach is Use the currentTarget property to reference the document element that called the event handler.
3. Event in the secondary DOM standard
Unlike IE, the Event object in the W3C DOM is not an attribute under the window global object. In other words, event is not a global variable. Usually in the DOM secondary standard, event is used as an attribute of the document object where the event occurs. Event contains two sub-interfaces, namely UIEvent and MutationEvent. These two sub-interfaces implement all methods and properties of Event. The MouseEvent interface is a sub-interface of UIEvent, so it implements all methods and properties of UIEvent and Event. Next, let's take a look at the main properties and methods of Event, UIEvent and MouseEvent.
 1.Event
  Type: Event type, similar to IE, but without the "on" prefix, for example, the click event is just "click".
Target: The node where the event occurs.
CurrentTarget: The node where the event currently being processed occurs, may be the node pointed to by the Target attribute, or may point to the parent node of the node pointed to by Target due to capture or bubbling.
EventPhase: Specifies the stage of event propagation. is a number.
timeStamp: The time when the event occurred.
Bubbles: Indicate whether the event is bubbled.
Cancelable: Indicate whether the event can use the preventDefault() method to cancel the default action.
  preventDefault() method: Cancel the default action of the event;
  stopPropagation() method: Stop event propagation.
 2.UIEvent
  View: The window object where the event occurred.
Detail: Provide additional information about the event. For click events, mousedown and mouseup events, they all represent the number of clicks.
 3.MouseEvent
 Button: A number indicating the state of the mouse button in mousedown, mouseup and click events. It is similar to the button attribute in IE, but the meaning of the number is different. 0 represents the left button. , 1 represents the middle button, 2 represents the right button.
 altKey, ctrlKey, shiftKey, metaKey: the same as IE, but IE does not have the last one.
ClientX, clientY: have the same meaning as IE, but in the DOM standard, these two attribute values ​​do not consider the scrolling situation of the document. That is to say, no matter where the document is scrolled, as long as the event occurs in the upper left corner of the window, clientX and clientY are both 0, so in IE, if you want to get the coordinates of the event relative to the beginning of the document, you need to add document.body.scrollLeft and document.body.scrollTop.
ScreenX, screenY: The position of the mouse pointer relative to the upper left corner of the monitor. If you want to open a new window, these two properties are very important.
RelatedTarget: Similar to fromElement and toElement in IE, except for mouseover and mouseout, other events have no meaning.
(3) Examples of dragging DOM elements compatible with two mainstream browsers
Okay, I just talked about so many DOM programming and events in IE, so how to write a browser that is compatible with both IE and Mozilla Firefox? What about browser drag and drop programs? The code is as follows:
Copy code The code is as follows:

function beginDrag(elementToDrag,event)
{
var deltaX=event.clientX-parseInt(elementToDrag.style.left);
var deltaY=event.clientY-parseInt(elementToDrag.style.top);

if(document.addEventListener)
{
document.addEventListener("mousemove",moveHandler,true);
document.addEventListener("mouseup",upHandler,true);
}
else if(document.attachEvent)
{
document.attachEvent("onmousemove",moveHandler);
document.attachEvent("onmouseup",upHandler);

}

if(event.stopPropagation) event.stopPropagation();
else event.cancelBubble=true;
if(event.preventDefault) event.preventDefault();
else event.returnValue=false;

function moveHandler( e)
{
if (!e) e=window.event; //If it is an IE event object, then use window.event
//Global attributes, otherwise use the DOM secondary standard Event object.
elementToDrag.style.left=(event.clientX-deltaX) "px";
elementToDrag.style.top=(event.clientY-deltaY) "px";

if(event. stopPropagation) event.stopPropagation();
else event.cancelBubble=true;

}

function upHandler(e)
{
if(document.removeEventListener)
{
document.removeEventListener("mouseup",upHandler,true);
document.removeEventListener("mousemove",moveHandler,true);}
else
{
document.detachEvent ("onmouseup",upHandler);
document.detachEvent("onmousemove",moveHandler);}
}
if(event.stopPropagation) event.stopPropagation();
else event.cancelBubble= true;
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn