First, let's introduce event bubbling and event capture.
The processing mechanism for events in the browser defaults to event bubbling, for example
<div id= ' div1 ' >
<div id= ' div2 ' >
<div id= ' div3 ' ></div>
</div>
</ Div>
#div1 {
width:500px;height:500px;
Background:rgb (12,42,31);
}
#div2 {
width:450px;height:450px;
Background:rgb (212,142,1);
}
#div3 {
width:350px;height:350px;
Background:rgb (1,242,153);
}
Bind Click event:
Div1.onclick=function () {
alert ("Div1")
}
div2.onclick=function () {
alert ("Div2")
}
div3.onclick=function () {
alert ("Div3")
}
At this point, when the single hit between the Div3, successively pop-up div3, Div2, Div1, this is the event bubbling process. With AddEventListener, you can set the event-handling mechanism to capture or bubble:
Div1.addeventlistener (' click ', function (obj) {
alert ("Div1")
},true);//If not false, event bubbling, not filled, default false
Div2.addeventlistener (' click ', function (obj) {
alert ("Div2")
},true);
Div3.addeventlistener (' click ', function (obj) {
alert ("Div3")
},true);
This sets the third argument to true, specifying that the event-handling mechanism is captured for the event. When you click Div3 again, the Div1, Div2, and Div3 will pop up in turn, as opposed to the previous.
In IE, only event bubbling, and there is no AddEventListener event, replaced by Attachevent.
But sometimes, we don't like to have events bubbling or capturing, and when I click Div3, we just pop div3. The following method is used to block event bubbling.
1. Block Bubbling events
is primarily used to prevent event propagation. Prevents it from being assigned to other DOM nodes and can be used at any stage of the event propagation. Use the following method (compatible IE):
function Stopbubble (event) {
if (window.event) {//compatible IE
window.event.cancelbubble=true;
} else{
event.stoppropagation ();
}
2. Block Default Events
A form element such as submit will bind to the default event, and other methods of the binding will not work if the default event is not blocked. Use the following method (compatible IE):
function Stopdefaultevent (event) {
if (window.event) {//compatible IE
window.event.returnvalue=false;
} else{
Event.preventdefault ()
} return
false;
}