In this article you will see
- What problem does the DOM event model solve
- What is capture and what is bubbling
- Can capture and bubbling be cancelled
What is the DOM event model
- Let’s start with this code:
<div class='grandpa'>
<div class='dad'>
<div class='son'>content</div>
</div>
</div>
Copy the code
FnGrandpa /fnDad/fnSon; fnGrandpa/fnDad/fnSon
- When users click on content, they click
grandpa
ordad
orson
? - The user clicks “Content” and calls first
fnGrandpa
/fnDad
/fnSon
Which function in?
The answer is ambiguous: yes, both.
- The peacemakers, the W3C, set the rules
To address these two issues, the W3C published a standard document in 2002 that provides the following:
- Browsers should support both call sequences
- See if there are functions listening in the order from outside to inside (grandpa > Dad > son), and then see if there are events listening in the order from inside to outside (son > Dad > Grandpa)
- If there are listener functions, call them and provide event information. If not, skip them
This is where DOM events come from
What is capture and what is bubbling?
See if there are functions listening in the order from outside to inside (grandpa > Dad > son), and then see if there are events listening in the order from inside to outside (son > Dad > Grandpa)
In this rule, looking for listeners from the outside in is called event capture, and looking for listeners from the inside out is called event bubble. By default, browsers catch listeners first and then bubble
- The complete DOM event model is divided into three phases:
- Capture Phase
- Target Phase
- Bubbling Phase
The target stage refers to the stage where the real target node is processing events, such as the user clicking “content” in the code above.
- We can choose whether to put the listener in the capture or bubble phase
- Event binding API
// IE5 dad.attachEvent('onclick',fn) / / the bubbling / / netscape dad.addEventListner('click',fn) / / capture / / the W3C USES dad.addEventListener('click', fn, bool) Copy the code
- when
bool
No parameter is passed orfalsy
.fn
Put it in the bubble stage - when
bool
Is true,fn
Put in the capture phase
Can capture and bubbling be cancelled
- Capture cannot be cancelled, but bubbling can
- You can use
e.stopPropagation()
Interrupt the bubbling
- You can use
- You cannot block the default action
- For example, scroll event, Scroll Event has two properties
Bubbles
Indicates whether the event bubblesCancelable
Refers to whether the developer can block the default event
- For example, scroll event, Scroll Event has two properties
- All bubbles can be cancelled
- Cancelale is not associated with bubbling