How much do you know about event trapping and bubbling?

1. Basic concepts

  • Capture: top down
  • Bubbling: Bottom up

2. Window. addEventListener Listens to what phase of events

// Bubble phase window.adDeventListener (‘click’, () => {

})

// Capture phase

window.addEventListener(‘click’, () => {

}, true)

3. What common scenarios use this mechanic?

Event delegation

4. A history page with click logic for several buttons, each with its own click event.

The new requirement is to add an attribute, banned = true, to every user who visits the page, which does not respond when the user clicks on a girl or element. It’s a direct alert that you’re banned.

window.addEventListener('click'.() = > {
  if(banned === true) { e.stopProgagtion(); }},true)
Copy the code

Demo sample

  1. html
<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <style>
    #parent {
      background-color: antiquewhite;
      padding: 50px;
    }

    #child {
      background-color: brown;
      padding: 50px;
    }

    #son {
      background-color: chartreuse;
      padding: 50px;
    }
  </style>
</head>

<body>
  <div id="parent">
    <div id="child">
      <div id="son"></div>
    </div>
  </div>
</body>

</html>

<script src="./index.js"></script>2) js ```javaScript const parent = document.getElementById('parent') const child = document.getElementById('child') Const son = document.getelementById ('son') window.addeventListener ('click', (e) => {console.log('window capture ')}, True) parent. AddEventListener ('click', (e) => {console.log('parent catch ')}, true) child.adDeventListener ('click', (e) => {console.log('child ')}, true) son.adDeventListener ('click', (e) => {console.log('son ')}, True) window.adDeventListener ('click', (e) => {console.log('window bubble ')}) parent. AddEventListener ('click', (e) => {console.log('parent bubble ')}) child.addeventListener ('click', (e) => {console.log('child bubble ')}) son.adDeventListener ('click', (e) => {console.log('son bubble ')})Copy the code