Bubbling and capturing
2018-06-05 本文已影响0人
TRYao
Let’s start with an example.
This handler is assigned to <div>
, but also runs if you click any nested tag like <em>
or <code>
:
<div onclick="alert('The handler!')">
<em>If you click on <code>EM</code>, the handler on <code>DIV</code> runs.</em>
</div>
edit it on codepen
Isn’t it a bit strange? Why the handler on <div>
runs if the actual click was on <em>
?
Bubbling
The bubbling principle is simple.
When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
Let’s say, we have 3 nested elements FORM > DIV > P
with a handler on each of them:
<style>
body * {
margin: 10px;
border: 1px solid blue;
}
</style>
<form onclick="alert('form')">FORM
<div onclick="alert('div')">DIV
<p onclick="alert('p')">P</p>
</div>
</form>
edit it on codepen
A click on the inner <p> first runs onclick:
- On that <p>.
- Then on the outer <div>.
- Then on the outer <form>.
- And so on upwards till the document object.
So if we click on <p>, then we’ll see 3 alerts: p → div → form.
The process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water.