On the sequence of event capture and event bubbling

Doubaojun 2021-02-23 04:04:22
sequence event capture event bubbling


@ About the sequence of event capture and event bubbling

create by db on 2021-2-21 14:33:31
Recently revised in 2021-2-21 16:00:35

Have a tight mind in your spare time , When you are busy, have a leisurely interest

Catalog

Preface

Return directory

I hear and I fogorget.

I see and I remember.

I do and I understand.

As a front-end Developer ,DOM Is one of our most familiar partners —— Every day F11 You can see it .

however , Do you really understand it ? Can you describe the sequence of event capture and event bubbling ?

If I can't remember for a moment , Let's go and have a look .

Text

Return directory

DOM The three stages of event flow

Events are propagated between element nodes in a specific order when they occur , This communication process is DOM Flow of events

When one DOM When the event is triggered , It's not just triggered once on its own object , It's going through three different stages :

  1. Capture phase (Capture Phase):
  • When we're in DOM Something happened to a node of the tree ( For example, click 、 Mouse over ), There will be an event launched in the past . This incident started from Window issue , Continue to pass through the lower nodes until the target node is triggered . The process before reaching the target node , It's the capture phase (Capture Phase).( All the nodes that pass through , Will trigger this event . The task of the capture phase is to establish the event routing , So that the later bubbling stage can follow this route back Window.) The capture event handler registered on the target element object itself is not called .
  1. Target stage (Target Phase):
  • When events continue to pass to the target node , Finally, this event is triggered on the target node , It's the goal stage .
  1. bubbling phase (Bubbling Phase):
  • Then trace back from the target event location to the root node of the document , Bubbling event objects from the inside out ( The event binding we usually use is the principle of event bubbling )

As shown in the figure :

The sequence of event capture and event bubbling is obvious .

DOM Element binding js The way of the event :

onclick

stay html Tag or by assignment onclick event , rewrite onclick Will override the previous properties , Only bubble phase is supported , There is no compatibility issue

The binding event :element.onclick = function(){}

Unbind event :element.onclick = null

addEventListener

IE8 The following is not supported , Belong to DOM2 Level method , You can add multiple methods that are not overridden

Parameter description :

  • event, must . character string , Specify the event name . Do not use "on" Prefix . for example , Use "click" , Instead of using "onclick".

  • function must . Specifies the function to be executed when the event is triggered , Note that only the function name is written , No parentheses .

  • useCapture Optional . Boolean value , Specifies whether the event is executed during the capture or bubble phase .

The binding event :

element.addEventListener(
'click',
function (e) {
e.preventDefault() // Block default events 
},
false
)
 Copy code 

Unbind event :

element.removeEventListener('click',function(){},false)

attachEvent

IE specific , compatible IE8 Up to , You can add multiple event handlers , Only bubble phase is supported

Parameter description :

  • event, must . character string , Specify the event name . Pay attention to the... In front of the event “on”, such as “onclick” and “onmouseover”, This is the addEventListener The difference between .
  • function The event listener function to bind , Note that only the function name is written , No parentheses .

The binding event :

element.attachEvent('onclick', function (e) {
e.returnValue = false // Block default events 
})
 Copy code 

Unbind event : element.detachEvent("onclick",function(){})

Code up , Experimentalize

open Online editor ---> jsbin.com/cedorat/edi…

The code is as follows :

</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#outer {
text-align: center;
width: 400px;
height: 400px;
background-color: yellow;
margin: 0 auto;
}
#middle {
width: 250px;
height: 250px;
background-color: red;
margin: 0 auto;
}
#inner {
width: 100px;
height: 100px;
background-color: green;
margin: 0 auto;
}
</style>
</head>
<body>
<div id='outer'>
<span>outer</span>
<div id='middle'>
<span>middle</span>
<div id='inner'>
<span>inner</span>
</div>
</div>
</div>
<script>
// First bind all capture events, then bind all bubble events 
on("outer", "click", o_click_c, true);
on("middle", "click", m_click_c, true);
on("inner", "click", i_click_c, true);
on("outer", "click", o_click_b, false);
on("middle", "click", m_click_b, false);
on("inner", "click", i_click_b, false);
// // First bind all bubble events, then bind all capture events 
// on("outer", "click", o_click_b, false);
// on("middle", "click", m_click_b, false);
// on("inner", "click", i_click_b, false);
// on("outer", "click", o_click_c, true);
// on("middle", "click", m_click_c, true);
// on("inner", "click", i_click_c, true);
// One by one binding capture and bubble events 
// on("outer", "click", o_click_c, true);
// on("outer", "click", o_click_b, false);
// on("middle", "click", m_click_c, true);
// on("middle", "click", m_click_b, false);
// on("inner", "click", i_click_c, true);
// on("inner", "click", i_click_b, false);
// Bind bubble and capture events one by one 
// on("outer", "click", o_click_b, false);
// on("outer", "click", o_click_c, true);
// on("middle", "click", m_click_b, false);
// on("middle", "click", m_click_c, true);
// on("inner", "click", i_click_b, false);
// on("inner", "click", i_click_c, true);
// Select the appropriate element 
function $(element) {
return document.getElementById(element);
}
// Binding method 
function on(element, event_name, handler, use_capture) {
if (addEventListener) { // All major browsers , except IE 8 And earlier IE edition 
$(element).addEventListener(event_name, handler, use_capture);
} else { // IE 8 And earlier IE edition 
$(element).attachEvent('on' + event_name, handler);
}
}
function o_click_c() {
console.log("outer_ Capture ");
}
function m_click_c() {
console.log("middle_ Capture ")
}
function i_click_c() {
console.log("inner_ Capture ")
}
function o_click_b() {
console.log("outer_ Bubbling ")
}
function m_click_b() {
console.log("middle_ Bubbling ")
}
function i_click_b() {
console.log("inner_ Bubbling ")
}
</script>
</body>
</body>
</html>
 Copy code 

In the above code , We define four execution orders :

  1. First bind all capture events, then bind all bubble events

  2. First bind all bubble events, then bind all capture events

  3. One by one binding capture and bubble events

  4. Bind bubble and capture events one by one

One 、 First bind all capture events, then bind all bubble events

Let's run the first one first :

  1. Click on outer, Print the results :
"outer_ Capture "
"outer_ Bubbling "
 Copy code 
  1. Click on middle, Print the results :
"outer_ Capture "
"middle_ Capture "
"middle_ Bubbling "
"outer_ Bubbling "
 Copy code 
  1. Click on inner, Print the results :
"outer_ Capture "
"middle_ Capture "
"inner_ Capture "
"inner_ Bubbling "
"middle_ Bubbling "
"outer_ Bubbling "
 Copy code 

Conclusion :

  • First, capture events from outside to inside , All the way to the incident element , And then bubble from the inside out to the root node

Two 、 First bind all bubble events, then bind all capture events

Let's run the second one first :

  1. Click on outer, Print the results :
"outer_ Bubbling "
"outer_ Capture "
 Copy code 
  1. Click on middle, Print the results :
"outer_ Capture "
"middle_ Bubbling "
"middle_ Capture "
"outer_ Bubbling "
 Copy code 
  1. Click on inner, Print the results :
"outer_ Capture "
"middle_ Capture "
"inner_ Bubbling "
"inner_ Capture "
"middle_ Bubbling "
"outer_ Bubbling "
 Copy code 

Conclusion :

  • In the capture phase, events are captured from outside to inside , In the bubbling phase, bubbles from the inside out to the root node

  • The target element first performs the bubble event , Then execute the capture event

3、 ... and 、 One by one binding capture and bubble events

Let's run the third one first :

  1. Click on outer, Print the results :
"outer_ Capture "
"outer_ Bubbling "
 Copy code 
  1. Click on middle, Print the results :
"outer_ Capture "
"middle_ Capture "
"middle_ Bubbling "
"outer_ Bubbling "
 Copy code 
  1. Click on inner, Print the results :
"outer_ Capture "
"middle_ Capture "
"inner_ Capture "
"inner_ Bubbling "
"middle_ Bubbling "
"outer_ Bubbling "
 Copy code 

Conclusion :

  • Same as the first one , First, capture events from outside to inside , All the way to the incident element , And then bubble from the inside out to the root node

Four 、 Bind bubble and capture events one by one

Let's run the fourth one first :

  1. Click on outer, Print the results :
"outer_ Bubbling "
"outer_ Capture "
 Copy code 
  1. Click on middle, Print the results :
"outer_ Capture "
"middle_ Bubbling "
"middle_ Capture "
"outer_ Bubbling "
 Copy code 
  1. Click on inner, Print the results :
"outer_ Capture "
"middle_ Capture "
"inner_ Bubbling "
"inner_ Capture "
"middle_ Bubbling "
"outer_ Bubbling "
 Copy code 

Conclusion :

Same as the second one

  • In the capture phase, events are captured from outside to inside , In the bubbling phase, bubbles from the inside out to the root node

  • The target element first performs the bubble event , Then execute the capture event

summary

Return directory

Event flow execution sequence

Through the above code , We can see that , About the sequence of event capture and event bubbling :

  1. In the capture phase , Capture events are executed from the outside in first ;

  2. When an event triggers In the goal phase when , It will be executed according to the sequence of event registration . That is to say, if there is a bubble event registered in the Department , Also registered capture events , be Follow the order of registration ;

  3. In bubbling stage , Bubbling from the inside out to the root node .

other :

  1. js Code can only perform one of the capture or bubble phases ( It's either catching or bubbling )

  2. onclick and attachevent(ie) You can only get the bubbling stage

  3. In development , We rarely use event capture , We're more concerned about the bubbling of events

  4. Some events are not bubbling , such as onblur、onfocus、onmouseenter、onmouseleave

  5. The bubbling of events can sometimes cause trouble , But it can be stopped , The method is :stopPropagation()

  • stopPropagation() Method : Capture of termination event in propagation process 、 Target processing or bubbling phase further spread . After calling this method , The handler on this node that handles this event will be called , Events are no longer assigned to other nodes .

What a long long road! , Share with you .

reference :

Postscript :Hello friends , If you think this article is good , Remember to like or give star, Your praise star It's my motivation to write more and richer articles !GitHub Address

Document protocol

 Creative Commons license agreement
db Document library for from db use Knowledge sharing A signature - Noncommercial use - Share in the same way 4.0 The international license agreement Licensing .
be based on github.com/danygitgit Creation of works on .
Use rights other than those authorized by this license agreement can be obtained from creativecommons.org/licenses/by… To obtain .

版权声明
本文为[Doubaojun]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210223024103883L.html

  1. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  2. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  3. Vue determines whether the El form in the elementui is updated or changed. If it changes, it will prompt whether to save it. If it does not change, it will leave directly
  4. Algorithm problem: sum of two numbers -- JavaScript and Java implementation
  5. High performance nginx HTTPS tuning
  6. JQuery advanced
  7. day 30 jQuery
  8. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  9. TCP/IP 开胃菜 之 HTTP
  10. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  11. JavaScript data type
  12. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  13. Solve Ajax cross domain problem [5 solutions]
  14. HTTP of TCP / IP appetizer
  15. Optimization of pod creation efficiency in serverless scenario
  16. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%
  17. First knowledge of HTTP / 1.1
  18. First knowledge of HTTP / 1.1
  19. Webpack learning notes series 05 devserver
  20. Webpack learning notes series 04 - resource processing optimization
  21. How to build a high performance front end intelligent reasoning engine
  22. How to become a professional front end engineer in 2021?
  23. How to transform single / micro service application into serverless application
  24. How to transform single / micro service application into serverless application
  25. How to transform single / micro service application into serverless application
  26. How to connect the ground gas to the micro front end?
  27. How to connect the ground gas to the micro front end?
  28. How to connect the ground gas to the micro front end?
  29. Vue server rendering principle analysis and introduction
  30. Realize the correct loading of text message
  31. Building my own project scaffolding with yeoman
  32. JavaScript advanced prototype and prototype chain
  33. React background management front end system (based on open source framework development) start
  34. JS practical skills breakpoint debugging
  35. I'd like to share with you 20 super easy-to-use Chrome extension plug-ins
  36. Get page element location
  37. Use the powerful API of modern browser to record any interface in the browser and realize export, save and management
  38. Delayed code execution in flutter
  39. Reconfiguration experience of KOA middleware system
  40. Add comments to your blog
  41. Svg editor -- new path
  42. Detailed explanation of debounce and throttle of JavaScript function
  43. Anti shake and throttling and corresponding react hooks package
  44. C2m: the first CSDN article moved to MOOC script 5000 words, detailed painstaking development process, there are renderings and source code at the end of the article
  45. Front end, school recruitment, Taobao, guide
  46. [vue2 & G6] get started quickly
  47. Canvas from the beginning to the pig
  48. Take five minutes to standardize the code comments?
  49. Some thoughts on sass
  50. what?! You haven't filled in the award information yet
  51. How to get the interface + tsdoc needed by TS through swagger
  52. Binary tree
  53. Canvas drawing method in Web screenshot
  54. Front end docker image volume optimization (node + nginx / node + multi-stage construction)
  55. Become a big influence of technology? Coding pages quickly build personal blog
  56. Object and array deconstruction, spread operator, rest operator
  57. Analysis of Axios source code
  58. Two ways to delete useless code in project (Practical)
  59. Edit your picture with canvas
  60. Today's chat: 2-4 years to walk out of the resignation dilemma and comfort zone