Event bubble and capture in JavaScript

JJesson 2021-02-22 23:53:46
event bubble capture javascript


Event bubble and event capture

cause : Today, I'm encapsulating a bind Function , Find out el.addEventListener The function supports the third parameter ,useCapture: Whether to use event capture , I feel a little fuzzy


  • Js Flow of events

    Which part of the page has a particular event , Example : Draw a set of concentric circles on the paper , If you put your fingers on concentric circles , So it's not a circle , It's all the circles on the paper . On the page, too , If you click a button , Also click the container element of the button , Even click on the whole page

    Flow of events : The order in which the page receives events ,IE and Netscape Two concepts were put forward at the beginning , Two kinds of The event bubbled , Event capture flow

 <!-- If there is such a similar passage html -->
<!DOCTYPE html>
<html>
<head><title>bubbling and capture</title></head>
<body>
<div id="myDiv">Click me</div>
</body>
</html>
  • Event Bubbling (event bubbling)

    IE The proposed event handling method , namely At the beginning of the event , Received by the most specific element , Then it propagates up to the unspecific nodes

    If you click... In the example div Elements , So this click The sequence of events spread is as follows :div -> body -> html -> document

    in other words ,click First of all, the event will be div Trigger on element , This element is what we click on , then click Events will follow DOM The trees spread up , It happens at every level of the node , Until it spread to document object

    All browsers support event bubbling , But there will be some differences in the specific implementation , for example IE5.5 And earlier versions of event bubbling will skip Html Elements , Directly from body Jump to the document Elements , and IE9,Firefox,Chrome,Safari Then bubble the event all the way to window object

  • Event capture (event capturing)

    Netscape The net well team has another flow of events called Event capture , The idea of event capture is that less specific nodes should receive events earlier , And the specific node should finally receive the event , The purpose of event capture is to capture an event before it reaches its expected goal , If you still take the above example , single click div

    So the trigger sequence would be like this document -> html -> body -> div

    In the event capture process ,document Object first receives click event , And then events along DOM The trees go down in turn , All the way to the actual goal of time, that is div Elements

    although Netscape It's about developing this flow of events , But now all the newer browsers support this event flow model , Even though “DOM2 Level event ” The specification requires that events should be from document Objects start to spread , But these browsers are all from window Object starts capturing Events

    Because older browsers don't support , So event capture is rarely used , It is recommended to use the event bubbling , Use event capture when there are special needs

  • DOM Flow of events

    "DOM2 Level events " What is? DOM2 Level The specified event flow consists of three phases

    Event capture phase At the target stage Event bubbling stage
    The event is not at the target , Events are delivered from large to small , From the outside down DOM The tree passes , Trigger sequence , From the outside to the inside At the target stage : The event occurs on the target element , And it's part of the bubbling phase of event handling Event bubbling stage : The event starts with the target element , Along DOM The trees pass out , Go to the parent container ,body,html,document Some browsers will arrive at window
  • What is? DOM2 Level ? What is? DOM0 Level ? What is? DOM Event handler level

    event : An action performed by the user or the browser itself , for example click,load,mouseover It's all the names of the events , And the function corresponding to an event , It's called Event handler , The event handler is named after on start , for example click The event handler is onclick,load The way to deal with the incident is onload

    • HTML Event handler

      Some html Element supports some kind of event , You can use a... With the same name as the corresponding time handler html Property to specify , The value of this property is executable javascript Code , for example

      <div onclick="alert(1)"></div>
      

      This event is triggered by : The bubbling phase triggers

    • DOM0 Level event handler

      html Event handler Of javascript Logic and html Too much coupling

      DOM0 Level event handler

       var btn = document.getElementById('myBtn')
      btn.onclick= function(){
      alert(this.id)
      }
      

      Here this It points to this trigger element , And through this Object to access any attributes and methods of an element , The event handler added in this way will be in the The bubbling phase is dealt with

      Remove event monitoring btn.onclick = null

    • DOM2 Level event handler

      Two methods :addEventListener and removeEventListener

      be-all DOM The node contains both methods , And take three parameters , Event name to process , Function as an event handler and a Boolean value , Finally, if this Boolean value is true, It means that The capture phase calls the event handler , If it is false It means in The bubble phase calls the event handler

      And the sequence of event flows is Capture - The goal is - Bubbling , The capture phase is before the bubbling event is handled , So instead of true It may affect the normal time sequence

      demo as follows :

       var btn = document.getElementById('myBtn')
      btn.addEventListener('click',function(){
      alert(this.id)
      },false)
      

      DOM2 The advantage of adding event handlers with the level method is that you can add multiple event handlers , The first two replace the event handler , Because there's only one attribute , And the method of the element will also override

      But it also means , Event handlers cannot be removed by rewriting , So pass removeEventListener To remove the event handler , And anonymous functions cannot be removed

      Most of the time , Both add event handlers to the bubbling phase of the event flow , In this way, all kinds of browsers can be compatible to the maximum extent , It's best to add an event handler to the capture phase only when you need to intercept an event before it reaches the target , If it's not particularly necessary , Registering event handlers in the time capture phase is not recommended

    • IE Event handler

      IE In this way, we can realize the connection with DOM Two similar methods in attachEvent and detachEvent, But only two parameters are accepted , One is the name of the event handler and the event handler function , because IE8 And earlier versions only support event bubbling , So pass attachEvent Any added event handler will be added to Event bubbling stage

      It should be noted that :

      1.attachEvent and DOM The main difference is in the scope of the event handler ,DOM0 Level will be in the scope of the element to which it belongs , and attachEvent The event handler runs in the global scope , So in attachEvent In the added function ,this Point to window

      2.attachEvent When adding multiple events , Not in the order of addition , But in reverse order , Add , Execute first

summary

  • el.addEventListener The third parameter problem of the function is solved , Use this method to represent the binding DOM2 Level event listener , It can be specified repeatedly , The third parameter indicates whether the event is handled in the capture phase , Capture -》 The goal is -》 Bubbling
  • The third parameter defaults to false, If there is no special case, it is not recommended to use the time processing program in the capture phase
  • I understand Flow of events , Capture and bubble ,DOM Event type level (HTML Level event handler ,DOM0 Level event handler ,DOM2 Level event handler ,IE Event handler )
  • Event flow process , First from the outside to the inside , Capture phase , Reach the target stage , Bubbling from the inside out
版权声明
本文为[JJesson]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210222151202063M.html

  1. Vue3元件(九)Vue + element-Plus + json = 動態渲染的表單控制元件
  2. 我的 HTTP/1.1 好慢啊!
  3. Vue為何採用非同步渲染
  4. The response status was 0. Check out the W3C XMLHttpRequest Level 2 spec for
  5. Front end monastery
  6. How to quickly understand a new front end project?
  7. webpack4.X核心工具库之tapable实例对象Hook
  8. webpack4.X核心工具库之tapable实例对象Hook
  9. C++使用libcurl进行http通讯
  10. Can be directly used in HTML special character table Unicode character set
  11. C++使用libcurl进行http通讯
  12. Java traverses list < string > and takes out the string elements in it, and splices them with ","
  13. Self taught web front end more than two months, talk about my harvest and progress, learning summary
  14. vue 中使用 css 变量
  15. 深入了解React中state和props的更新
  16. 百度分享不支持https的解决方案
  17. [practical] ABAP mail sending (HTML + attachment)
  18. [practical] ABAP mail sending (HTML + attachment)
  19. Teach you how to select products with less profit and competition in Amazon Product Development (1)
  20. 【微前端】微前端最终章-qiankun指南以及微前端整体探索
  21. 【微前端】微前端最终章-qiankun指南以及微前端整体探索
  22. Vue-Cli 创建vue3项目
  23. Go in the front of the progress of u boot v7.0 U disk boot disk production tools
  24. 使用NTLM的windows身份验证的nginx反向代理
  25. Rust教程:针对JavaScript开发人员的Rust简介
  26. 使用 Serverless Framework 部署个人博客到腾讯云
  27. #研發解決方案#易車前端監控系統
  28. Vue changes localhost to IP address and cannot access
  29. JavaScript进阶学习
  30. HTML5 from entry to proficient, realize annual salary 10W +, zero basic students must see
  31. Vue:vuex状态数据持久化插件vuex-persistedstate
  32. Vue source code analysis - start
  33. Vue -- the child component calls the method of the parent component and passes parameters --- props
  34. React-Native 获取设备当前网络状态 NetInfo
  35. 高性能 Nginx HTTPS 调优 - 如何为 HTTPS 提速 30%
  36. How to learn HTML5? How can Xiaobai start HTML5 quickly?
  37. HTML + CSS detailed tutorial, this article is enough, but also quickly save
  38. JavaScript高级:JavaScript面向对象,JavaScript内置对象,JavaScript BOM,JavaScript封装
  39. Why Vue uses asynchronous rendering
  40. JavaScript高级:JavaScript面向对象,JavaScript内置对象,JavaScript BOM,JavaScript封装
  41. vue判断elementui中el-form是否更新变化,变化就提示是否保存,没变就直接离开
  42. 算法题:两数之和——JavaScript及Java实现
  43. 高性能 Nginx HTTPS 调优
  44. Why Vue uses asynchronous rendering
  45. day 31 jQuery进阶
  46. day 30 jQuery
  47. CSS whimsy -- using background to create all kinds of wonderful backgrounds
  48. Why are more and more people learning front end?
  49. What do you do with 4K front-end development?
  50. 8 years of front-end development knowledge precipitation (do not know how many words, keep writing it...)
  51. What is the annual salary of a good web front end?
  52. Front end novice tutorial! How to get started with web front end
  53. Will the front end have a future?
  54. Is the front end hard to learn?
  55. Seven new Vue combat skills to improve efficiency in 2021!
  56. Is front end learning difficult?
  57. How about the process of Web front-end development and self-study?
  58. Front end learning route from zero basis to proficient
  59. What is the basis of learning front end?
  60. What knowledge points need to be learned for self-study front end? How long can I become a front-end Engineer?