通常,事件处理程序在 bubbling 阶段运行。请注意,如果你在此示例中向 <input>
中输入某些内容,会发生什么 — 内部处理程序首先运行,作为从目标到文档的事件 ‘bubbles’,然后是外部处理程序。
¥Normally, event handlers run during the bubbling phase. Notice what happens if you type something into the <input>
in this example — the inner handler runs first, as the event ‘bubbles’ from the target up to the document, followed by the outer handler.
有时,你希望处理程序在捕获阶段运行。将 capture
添加到事件名称末尾:
¥Sometimes, you want handlers to run during the capture phase instead. Add capture
to the end of the event name:
App
<div onkeydowncapture={(e) => alert(`<div> ${e.key}`)} role="presentation">
<input onkeydowncapture={(e) => alert(`<input> ${e.key}`)} />
</div>
现在,相对顺序被反转了。如果给定事件同时存在捕获处理程序和非捕获处理程序,则捕获处理程序将首先运行。
¥Now, the relative order is reversed. If both capturing and non-capturing handlers exist for a given event, the capturing handlers will run first.
1
2
3
4
<div onkeydown={(e) => alert(`<div> ${e.key}`)} role="presentation">
<input onkeydown={(e) => alert(`<input> ${e.key}`)} />
</div>