DOM event model
When an event occurs, it propagates from child element to parent element, and this propagation is divided into three stages:
- Event capture: Look for listeners from the outside in – proposed by Microsoft
- Fires an event at the target node
- Event bubbling: Find listener functions from inside out – proposed by Netscape
W3C standard: Capture first, bubble later.
capture
When an event is triggered, the browser will automatically check whether there is the same event from the top TAB outside the user’s operation label. If there is, the event will be triggered. If not, the browser will continue to check until it reaches the user’s operation label. The process is capture.
The bubbling
At this point, the browser will continue to check the user operation TAB to the superior TAB. If the same event is detected, if not, the browser will continue to check and guide the superior until the highest level. This process is bubbling.
Take a simple example of a click event:
<div class="grandfather"> <div class="father"> </div>Copy the code
Capture: grandfather >. Father >. The son
Bubble: son >. Father >. Granfather
Add fnYe/fnBa/fnEr to each of these divs
Question 1: who did you click on when you click the text? Does that count as clicking son? fanter? grandfather? Answer: Both. Question 2: What is the order of the calls? A: Either.
The W3C uses the addEventListener event binding API to determine whether an event is triggered in the capture or bubble phase. W3C:baba.addEventListener(‘click’,fn,bool)
- If bool is left blank or falsy: then let fn go through the bubbling phase, that is, when the browser finds that BABA has fn’s listener function during the bubbling phase, it calls FN and provides the event information.
- If bool is true, let FN capture.
Target vs. currentTarget
- E.target is the user action element
- E.currenttarget is the element that the programmer listens on
For example:
<span> Text </span> </div>Copy the code
When the user clicks on text, e.target is span and E.currenttarget is div.
There is a special case: only one div is being listened on (regardless of both the parent and the child being listened on at the same time), and the FN listens for the click event in the capture phase and the bubble phase, respectively. What the user clicks on is what the developer listens for.
In this case, div.addeventLisenter (‘click’,f1) and div.addeventLisenter (‘click’,f2,true). Who will execute f1 or F2 first?
A: Who listens first, who executes first.
Cancel the bubbling
Capture cannot be cancelled, but bubbling can. Using e.topPropagation () to interrupt bubbling, the browser will no longer go up. Popular saying: someone beat me, I solve it, don’t tell my father.