Talking about JavaScript events and javascript
1. event stream
The event stream describes the sequence of events received from the page. However, IE proposes a bubble stream, While Netscape Communicator proposes a capture stream.
JavaScript event stream
2. event bubbling)
Events are received by the most specific elements (the node with the deepest nesting level), and then gradually spread to a node (document) that is not specific ). As follows:
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> event bubbling </title>
</Head>
<Body>
<Div id = "myDiv"> click me </div>
</Body>
</Html>
Window. onload = function (){
Var obj = document. getElementById ("test ");
Obj. onclick = function (){
Alert (this. tagName );
};
Document. body. onclick = function (){
Alert (this. tagName );
};
Document.doc umentElement. onclick = function (){
Alert (this. tagName );
};
Document. onclick = function (){
Alert ("document ");
};
Window. onclick = function (){
Alert ("window ");
}
};
Event propagation sequence: div --> body --> html --> document
Note:
All modern browsers support bubble events, but there are still some differences in implementation. Event bubbles in IE5.5 and earlier versions will jump directly from the body to the document (without html execution ). Firefox, Chrome, and Safari will always bubble events to the window object.
3. Stop event bubbling and cancel default events
A. Get the event object
Copy codeThe Code is as follows:
Function getEvent (event ){
// Window. event IE
// The event is not IE
Return event | window. event;
}
Function B: Stop event bubbles.
Copy codeThe Code is as follows:
Function stopBubble (e ){
// If the event object is provided, this is a non-IE browser
If (e & e. stopPropagation ){
// Therefore, it supports the W3C stopPropagation () method.
E. stopPropagation ();
} Else {
// Otherwise, we need to use IE to cancel event bubbling.
Window. event. cancelBubble = true;
}
}
C. prevent default browser behavior
Copy codeThe Code is as follows:
Function stopDefault (e ){
// Block the default browser action (W3C)
If (e & e. preventDefault ){
E. preventDefault ();
} Else {
// Block the default action of the function in IE
Window. event. returnValue = false;
}
Return false;
}