Understanding the event _javascript techniques in JavaScript

Source: Internet
Author: User
In many language learning, "event" is a relatively difficult to understand, but it is a very important concept. The same is true of event handling in JavaScript, which results from an AJAX drag because of event handling. This article discusses the event processing in JavaScript, and after reading it, you will know that many Ajax frameworks implement the principle of drag.
One, IE event object
(a) IE event object's main attributes and methods
In IE, there is a dedicated event processing object, this object is responsible for the handling of events, contains a lot of properties and methods, through these methods and properties of the call, can complete a lot of event processing.
Type: The types of events, which are the HTML tag properties, are strings that do not have an "on" prefix, such as "click" to represent the clicked event.
Srcelement: The event source is the element where the event occurred.
Button: Declares a pressed mouse button and is an integer. 1 on behalf of the left mouse button, 2 for the right mouse button, 4 for the middle of the mouse button, if you press a number of mouse keys, the values are added together, so 3 on behalf of the key at the same time press.
Clientx/clienty: Refers to when the event occurs, the mouse's horizontal, ordinate, returned an integer, their value is relative to the upper left corner of the containment window generated.
Offsetx/offsety: The position of the mouse pointer relative to the source element to determine which pixel of the image object to click.
Altkey,ctrlkey,shiftkey: As the name suggests, these properties refer to a Boolean value when the mouse event occurs, holding down the ALT, CTRL, or SHIFT keys at the same time.
KeyCode: Returns the code for the key and the Unicode character of the KeyPress event when the KeyDown and KeyUp events occur.
Fromelement, toelement the former refers to the document elements that are moved by the MouseOver event, which refers to the document element that the mouse moves to in the Mouseout event.
Cancelbubble: A Boolean property that, when set to true, will stop the event further bubbling to an containment-level element.
ReturnValue: A Boolean property that, when set to False, organizes the browser to perform the default event action, equivalent to <a href= "#" onclick= "Processmethod (); return false;"/>.
Attachevent () and DetachEvent () methods: A method for registering multiple event-handling functions for a DOM object event type, which has two parameters, the first is the event type, and the second is the event handler function. At the time the Attachevent () event is executed, the This keyword points to the Window object, not to the element where the event occurred.
(b) Some descriptions of IE event objects
1.IE Event object is a global property
In IE, an event object cannot be passed as a parameter to an incident handler, and only window.event or event can be referenced. Because in IE, event is a property of window, meaning that event is a global variable, which provides details of the event.
2.IE event bubbling: IE events can bubble up to the top of the containment layer a little bit, that is, the event handler function defined by the underlying DOM node, and the upper node if there is an event handler for the same event type as the lower level, then the event handler function is executed. For example, the,<div> tag contains the &LT;A&GT, and if both tags have a handler function for the OnClick event, the execution is performed by first executing the OnClick event handler for the <a> tag, and then executing <div> Event-handling functions. If you want the <a> event handler to finish executing, and you do not want to perform the upper <div> onclick event handler, set the cancelbubble to False.
  
Second, the example of dragging DOM elements in IE
Copy Code code as follows:

/*
This function is called by the MouseDown event handler
It registers a temporary capture event handler for the MouseMove and MouseUp events that occur subsequently
Use these event handlers to drag the specified document element
The second argument must be an event object for the MouseDown event
*/
function BeginDrag (elementtodrag,event)
{
Where is the element currently located
The style nature of the element must have left and top CSS properties
In addition, we assume that they use pixels as units
var x=parseint (elementToDrag.style.left);
var y=parseint (elementToDrag.style.top);

Calculates the distance between a point and a mouse click, and the following nested Movehandler function 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 occurred after registering the MouseDown event
Note that they are registered as capture event handlers for the document
These event handlers remain active when the mouse button is held in a pressed state
When the button is released, they are deleted.
Document.attachevent ("OnMouseMove", Movehandler);
Document.attachevent ("onmouseup", Uphandler);

We've dealt with the event and don't let the other elements see it
Event.cancelbubble=true;
Event.returnvalue=false;

/*
This is the handler that captures the MouseMove event when the element is dragged, and it responds to the moved 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 other elements see the event
Event.cancelbubble=true;
}

/*
This event will catch the MouseUp event that occurs when the drag ends
*/
function Uphandler (e)
{
Unregister an event handler
Document.detachevent ("onmouseup", Uphandler);
Document.detachevent ("OnMouseMove", Movehandler);}

Event.cancelbubble=true;
}
Call it's HTML file code:
<title>untitled page</title>
<script type= "Text/javascript" src= "Dragie.js" ></script>
<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
</div>
<div>
<p>this is a test. Testing,testing</p></div>
</div>
</body>

Iii. Advanced event Handling in the DOM
Event handling in IE 6 is not a standard event-handling model for the Web, so if the above code runs in Mozilla Firefox's browser, it will lose its effect, and the upcoming IE 7 will also support the two-level standard for the DOM of the Consortium, So it's important to master Dom's advanced event handling, because the two-level standard for the web is the direction of the future, while the API for the DOM is so common that it provides a good foundation for more complex web development in the future.
(i) Scope of event handlers and propagation of events
Before we formally discuss DOM advanced event processing, it is important to understand the scope of the event handlers. The scope of an event handler is much more complex than a normal function scope. Normal function scope chain is easier, for example, in a normal function to find a variable A, then the JavaScript interpreter will first in the call object of the function to find whether there is a variable, if not, will be in the scope of the next object in the chain, generally the global object to find. However, event handlers are not that simple, especially with HTML attributes, whose scope chain heads are the objects that call them, and the next object is not the global object, but the object that triggers the event handler. So there is a problem, window and document have a method open (), if the open () is not decorated before, then in the event-handling function will call the Document.open () method, rather than the common window.open () method, Therefore, the use of the time should be clearly specified is window.open ().
(ii) Event dissemination and registration of event handling procedures
1. Event dissemination
In the level two DOM standard, event handlers are more complex, and when an event occurs, the target node's event handler is triggered, but the target node's parent has the opportunity to handle the event. Events are propagated in three phases, first in the capture phase, from the Document object down the DOM tree to the target node, and if any parent node of the target registers a handler to capture the event, the event is run first in the process of propagation. The next stage is where the target node itself occurs, and the corresponding event handler that is registered on the target node executes, and finally the bubbling phase, the event is passed up from the target node back to the parent node, and also if the parent node has a corresponding event handler. In IE, there is no stage for capture, but there is a bubbling stage. You can use the Stoppropagating () method to stop event propagation, which means that other elements are not visible to this event, and in IE 6, the cancelbubble is set to true.
2. Registering an event handler
Like IE, the DOM Standard has its own event handlers, but DOM level two standard event handlers are more powerful than IE, and event handlers are registered with the Addeventlistner method, which has three parameters, the first is the event type, and the second is the processing function, The third one is a Boolean value, true means that an event handler is used to catch an event when the event is propagated, otherwise it is not captured, and when the event occurs on the object it triggers the function that executed the event, or occurs at the byte point of the object, and bubbles up onto the object. Triggers the function that performs this event handling. For example: Document.addeventlistener ("MouseMove", Movehandler,true), the Movehandler function is invoked when the MouseMove event occurs, and the event can be captured.
You can use AddEventListener to register multiple event-handling programs for an event, but the order in which these functions are executed is indeterminate and is not performed in the order of registration, as in C #.
When you register an event handler with AddEventListener in Mozilla Firefox, the This keyword represents the document element that invokes the event handler, but not necessarily in other browsers, because this is not a DOM standard. The correct approach is to use the Currenttarget property to refer to the document element that invokes the event handler.
3. Event in Level two DOM standard
Unlike IE, the event object in the Universal DOM is not a property under the Window global object, in other words, the event is not a global variable. Usually in the DOM level two standard, event acts as the property of the Document object where the event occurred. Event contains two sub-interfaces, respectively, Uievent and Mutationevent, which implement all the methods and properties of the event, while the MouseEvent interface is a uievent sub-interface. So all the methods and attributes of Uievent and event are implemented. Let's look at the main properties and methods of event, Uievent, and MouseEvent.
1.Event
Type: Event types, similar to IE but without "on" prefix, for example, click event is just "click".
Target: The node where the event occurred.
Currenttarget: The node in which the event is currently being processed may be the node pointed at by the target attribute, or it may be caught or blistered to point to the parent of the node that the target is referring to.
Eventphase: Specifies the phase of event propagation. is a number.
TimeStamp: The time the event occurred.
Bubbles: Indicates whether the event is bubbling.
Cancelable: Indicates whether the event can use the Preventdefault () method to cancel the default action.
Preventdefault () Method: Cancels the default action of the event;
Stoppropagation () Method: Stops event propagation.
2.UIEvent
View: The Window object where the event occurred.
Detail: Provides additional information about the event, which is the number of clicks that are represented by the click event, MouseDown, and MouseUp event.
3.MouseEvent
Button: A number that indicates the state of the mouse button in the MouseDown, MouseUp, and click events, similar to the button property in IE, but the number represents a different meaning, 0 for the left, 1 for the middle key, 2 for the right key.
Altkey, Ctrlkey, Shiftkey, Metakey: Same as IE, but IE is not the last one.
ClientX, ClientY: and IE have the same meaning, but in the DOM standard, these two attribute values do not consider the document scrolling, that is, no matter where the document scrolling, as long as the event occurs in the upper left corner of the window, ClientX and ClientY are 0, so in IE, To get the coordinates of the event to take place relative to the beginning of the document, add Document.body.scrollLeft and Document.body.scrollTop.
ScreenX, ScreenY: The position of the mouse pointer relative to the upper-left corner of the display, these two properties are important if you want to open a new window.
Relatedtarget: Similar to the fromelement and toelement in IE, other events have little meaning except for mouseover and Mouseout.
(iii) Examples of dragging DOM elements compatible with two major browsers
Okay, so much DOM programming and events in IE, how do you write a drag-and-drop program that is compatible with IE and Mozilla Firefox's two main browsers? The code is as follows:
Copy Code code 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's an IE event object, then use the window.event
Global properties, otherwise use the event object of the DOM level two standard.
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.