Bubble and capture mechanism of events
Standard dom event flow mechanism: when a child node is clicked, if the parent node also binds events in the way of capture, the execution order is first the parent node event, then the child node event
Our common event flow mechanism: it prevents the capture mechanism of the parent node, that is, the bubbling mechanism; that is, the child node event is executed first, and the parent node event is bubbled
Of course, bubbling can also be prevented; let's take the code as an example
1. Our common bubbling mechanism
<div class="box3">Parent node <div class="box4">Child node</div> </div>
.box3{ width: 200px; height: 200px; background: deepskyblue; margin-top: 50px; } .box4{ width: 100px; height: 100px; background: deeppink; }
let box3 = document.getElementsByClassName("box3")[0]; let box4 = document.getElementsByClassName("box4")[0]; box3.addEventListener("click",function () { console.log("The parent node has also been clicked") },false)//The third parameter is false, that is, the parent node does not bind events in the way of capture box4.addEventListener("click",function () { console.log("Child nodes clicked") },false)
So for this, we use the method of event listening to bind events
addEventListener(event,fun,useCaptuer) / / the first parameter: event; the second parameter: operation of this event, function body; the third parameter: capture or not
As mentioned above, bubbling is the first child node, then the parent node. Click the child node, so the execution result is:
2 event capture mechanism
<div id="parent" class="box1"> <div id="child" class="box2"></div> </div>
.box1{ width: 200px; height: 200px; background: deepskyblue; } .box2{ width: 100px; height: 100px; background: deeppink; }
let box1= document.getElementById("parent"); let box2= document.getElementById("child"); //Standard event flow, capture first and then bubble box2.addEventListener("click",function () { console.log("Child nodes clicked") },false) box1.addEventListener("click",function () { console.log("The parent node also performs event operations through event capture") },true)//The third parameter of the parent node is true, that is, the event is handled in the way of capture
Here, we click the sub node, and the final result is
Capture: when a dom event is triggered by mouse operation, the browser will start from the root node and propagate the event from the outside to the inside, that is, click on the child element. If the parent element registers the corresponding event through event capture, the event bound by the parent element will be triggered first
Bubbling: sequence of event execution, - inside out
Mechanism of preventing bubbling
Visit this website Click the blank to hide dom