Javascript event processing

Source: Internet
Author: User
In many languages, "events" are difficult to understand, but they are also a very important concept. The same is true for event processing in Javascript. It is precisely because of event processing that AJAX dragging will occur. This article will discuss the event processing in Javascript. After reading it, you will know how many Ajax frameworks implement the drag effect.
I. ie event object
(1) main attributes and methods of the IE event object
In IE, there is an object event that is responsible for event processing. This object is responsible for event processing and contains many attributes and Methods. Through these methods and attribute calls, you can complete a lot of event processing.
Type: the type of the event, which is a string without the "on" prefix in the HTML Tag attribute. For example, "click" indicates a click event.
Srcelement: The Event source, which is the element of the event.
Button: Declares the mouse key pressed, which is an integer. 1 indicates the left mouse button, 2 indicates the right mouse, and 4 indicates the middle mouse key. If Multiple mouse keys are pressed, these values are added together, SO 3 indicates that the left and right keys are pressed simultaneously.
Clientx/clienty: refers to the horizontal and vertical coordinates of the mouse when an event occurs, and return integers. Their values are generated relative to the upper left corner of the inclusive window.
Offsetx/offsety: the position of the mouse pointer relative to the source element. You can determine which pixel of the image object to click.
Altkey, ctrlkey, and shiftkey: as the name suggests, these attributes indicate whether ALT, Ctrl, or shift keys are simultaneously held when a mouse event occurs, and a Boolean value is returned.
Keycode: When the keydown and keyup events are returned Code And Unicode characters of the keypress event.
Fromelement and toelement refer to the document elements that the Mouseover event has moved, and the latter refer to the document elements that the mouse moves to in the mouseout event.
Cancelbubble: A boolean attribute. When it is set to true, the Stop event is further blister to the element of the inclusion level.
Returnvalue: A boolean attribute. When set to false, the browser can be organized to execute default event actions, which is equivalent to <a href = "#" onclick = "processmethod (); Return false; "/>.
Attachevent () and detachevent () Methods: Methods for registering multiple event handler functions for developing DOM object event types. They have two parameters. The first is the event type, the second is the event processing function. When the attachevent () event is executed, this keyword points to the window object, rather than the element where the event occurs.
(2) Description of the IE event object
1. the IE event object is a global attribute.
In ie, the event object cannot be passed to the event for processing as a parameter. Program , You can only use window. event or event to reference the event object. In IE, event is an attribute of window, that is, event is a global variable, which provides the event details.
2. event bubbles in IE: Events in IE can bubble up to the upper level a little along the tolerant level. That is to say, the lower Dom node defines the event handler function, if an event handler function of the same event type as that of the lower-layer node is added to the upper-layer node, the upper-layer event handler function is also executed. For example, the <div> label contains <A>. If both labels have The onclick event processing function, in this case, The onclick event processing function of the <A> label is executed first, and then the <div> event processing function is executed. If you do not want to execute the onclick event processing function of the Upper-layer <div> after the <A> event processing function is executed, set cancelbubble to false.

Ii. Example of dragging DOM elements in IE
/*
This function is called by processing the mousedown event.
It registers a temporary event capture handler for subsequent mousemove and mouseup events.
Use 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 attribute of the element must have the left and top CSS attributes.
// In addition, we assume that they use pixels as units.
// Var x = parseint (elementtodrag. style. Left );
// Var y = parseint (elementtodrag. style. Top );

// Calculate the distance between a point and a mouse click. These values are required by the nested movehandler function below.
VaR deltax = event. clientx-parseint (elementtodrag. style. Left );
VaR deltay = event. clienty-parseint (elementtodrag. style. Top );

// Process the mousemove and mouseup events that occur after the mousedown event is registered
// Note that they are registered as capture event handlers for the document
// When the mouse button is pressed, these Event Handlers remain active.
// When buttons are released, they are deleted.
Document. attachevent ("onmousemove", movehandler );
Document. attachevent ("onmouseup", uphandler );

// We have handled this event and don't let other elements see it.
Event. cancelbubble = true;
Event. returnvalue = false;

/*
This is the handler that captures the mousemove event when an element is dragged. It 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 ";

// Do not let other elements see the event
Event. cancelbubble = true;

}

/*
This event captures the mouseup event that occurs when the drag ends.
*/
Function uphandler (E)
{
// Deregister the event handler
Document. detachevent ("onmouseup", uphandler );
Document. detachevent ("onmousemove", movehandler );}

Event. cancelbubble = true;
}
Code for calling its HTML file:
<HTML>
<Head>
<Title> untitled page </title>
<SCRIPT type = "text/JavaScript" src = "dragie. js"> </SCRIPT>
</Head>
<Body>
<Div style = "position: absolute; left: 100px; top: 100px; Background-color: White; Border: solid black;">
<Div style = "background-color: Gray; border-bottom: solid black; padding: 3px; font-family: sans-serif; font-weight: bold; "onmousedown =" begindrag (this. parentnode, event); ">
Drag me & nbsp;
</Div>
<Div>
<P> This is a test. Testing, testing </P> </div>
</Div>
</Body>
3. Advanced event processing in Dom
The event processing in IE 6 is not the W3C Dom standard event processing model. Therefore, if the above Code runs in the Mozilla Firefox browser, it will become ineffective, at the same time, the upcoming release of IE 7 will also support the W3C Dom Level 2 standard, so it is very important to master Dom high-level event processing, because W3C Dom Level 2 standard is the future development direction of web, at the same time, W3C Dom APIs are very common and provide a good foundation for more complex web development in the future.
(1) scope of the event handler and dissemination of the event
Before formally discussing Dom high-level event processing, we need to understand the scope of the event processing program. The scope of an event handler is much more complex than that of a common function. The scope chain of a common function is relatively easy. For example, if a variable A is found in a common function, the javascript interpreter first checks whether the variable A exists in the call object of the function, if no, It will be located in the next object of the scope chain, generally the global object. However, event handlers are not that simple, especially those defined by HTML attributes. the header of their scope chain is the object that calls them, And the next object is not a global object, it is the object that triggers the event processing program. In this case, a problem occurs. Both window and document have a method open (). If open () is not modified before it, the document will be called in the event processing function. open () method, rather than common window. open () method, so it should be explicitly specified as window. open ().
(2) event propagation and registration of event handling procedures
1. Event Propagation
In the level-2 Dom standard, the event processing program is complicated. when an event occurs, the event processing program of the target node will be triggered for execution, however, the parent node of the target node also has the opportunity to handle this event. Event propagation is divided into three phases. The first is the capture phase. Events are propagated from the document object down the DOM tree to the target node, if any parent node of the target registers the event capture handler, the event first runs this sequence during propagation. The next stage occurs on the target node itself. The corresponding event handler registered on the target node will be executed. The final stage is the bubble stage, the event is returned from the target node to the parent node. Similarly, if the parent node has an event handler, the event will be processed. In IE, there is no capture stage, but there is a bubble stage. You can use the stoppropagating () method to stop event propagation, that is, make other elements invisible to this event. In IE 6, set cancelbubble to true.
2. register the event handler
Like IE, Dom standards also have their own event handlers. However, Dom Level 2 standard event handlers are more powerful than IE. The addeventlistner method is used for Event Handler Registration, this method has three parameters: the first is the event type, the second is the processing function, and the third is a Boolean value, true indicates that the specified event handler will be used to capture events in the event propagation phase. Otherwise, the event will not be captured. when an event occurs on an object, the function that executes the event processing will be triggered, or when it occurs on the object's byte point and bubbles up to this object, it triggers the function that executes the event processing. For example, document. addeventlistener ("mousemove", movehandler, true) is used to call the movehandler function and capture events when a mousemove event occurs.
You can use addeventlistener to register multiple event processing programs for an event. However, the execution sequence of these functions is uncertain and does not follow the registration sequence as C # does.
When using addeventlistener to register an event handler in Mozilla Firefox, this keyword indicates that the document elements of the event handler are called, but this is not necessarily true for other browsers, because this is not a DOM standard, the correct method is to use the currenttarget attribute to reference the document elements that call the event handler.
3. Event in Level 2 Dom Standard
Unlike ie, the event object in W3C Dom is not an attribute under the window global object. In other words, event is not a global variable. Generally, in the DOM Level 2 standard, event is the attribute of the Document Object where an event occurs. The event contains two sub-interfaces: uievent and mutationevent. These sub-interfaces implement all the methods and attributes of the event, and the mouseevent interface is a sub-interface of the uievent, therefore, all methods and attributes of uievent and event are implemented. Next, let's take a look at the main attributes and methods of event, uievent, and mouseevent.
1. Event
Type: event type, similar to IE, but with no "on" prefix. For example, if you click an event, it is only "click ".
Target: the node where the event occurs.
Currenttarget: the node where an event is being processed. It may be the node pointed to by the target attribute, or it may point to the parent node of the target node due to capture or blister.
Eventphase: Specifies the stage of event propagation. Is a number.
Timestamp: the time when the event occurred.
Bubbles: indicates whether the event is blister.
Cancelable: Specifies whether the event can use the preventdefault () method to cancel the default action.
Preventdefault () method: cancels the default action of an event;
Stoppropagation () method: Stop event propagation.
2. uievent
View: Window object in which an event occurs.
Detail: provides additional information about events. Click events, mousedown events, and mouseup events indicate the number of clicks.
3. mouseevent
Button: A number indicating the status of the mouse key in the mousedown, mouseup, and click events. It is similar to the button attribute in IE, but the number indicates a different meaning, and 0 indicates the left button, 1 indicates the intermediate key, and 2 indicates the right-click Key.
Altkey, ctrlkey, shiftkey, and metakey: The same as IE, but IE does not have the last one.
Clientx and clienty: they have the same meaning as IE, but in the DOM standard, the two attribute values do not consider the scrolling of the document, that is, no matter where the document is rolled, as long as the event occurs in the upper left corner of the window, both clientx and clienty are 0. Therefore, in IE, to get the coordinates of the event relative to the position starting with the document, add document. body. scrollleft and document. body. scrolltop.
Screenx and 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 attributes are very important.
Relatedtarget: similar to fromelement and toelement in IE, other events have no significance except for Mouseover and mouseout.
(3) Examples of dragging DOM elements compatible with two mainstream browsers
Well, I have talked about so many Dom programming and Internet Explorer events. How can I write drag-and-drop programs compatible with mainstream browsers IE and Mozilla Firefox? 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 event object of IE, use window. Event
// Global attribute. Otherwise, the DOM second-level standard event object is used.
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;

}

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.