通常,事件處理器會在冒泡階段執行。請注意,如果在此範例中於 <input>
輸入內容會發生什麼事 — 內部處理器會先執行,因為事件會從目標「冒泡」到文件,然後是外部處理器。
有時,您希望處理器在捕獲階段執行。請在事件名稱結尾新增 capture
App
<div onkeydowncapture={(e) => alert(`<div> ${e.key}`)} role="presentation">
<input onkeydowncapture={(e) => alert(`<input> ${e.key}`)} />
</div>
現在,相對順序顛倒了。如果給定事件同時存在捕獲和非捕獲處理器,則捕獲處理器將首先執行。
1
2
3
4
<div onkeydown={(e) => alert(`<div> ${e.key}`)} role="presentation">
<input onkeydown={(e) => alert(`<input> ${e.key}`)} />
</div>