1 回答
TA贡献1793条经验 获得超6个赞
直接在窗口上触发的事件窗口没有“捕获阶段” ”。
如果您查看事件调度和 DOM 事件流图形,您可以看到该流程开始于 窗口,因此此类事件将已处于“目标阶段”状态。从第一步开始。
这意味着对于此类事件,capture
标志是无用的,因为所有事件侦听器都将在“目标阶段”,因为它们会在您的捕获处理程序之前触发。您无法停止将事件传播到先前设置的处理程序”无论如何,所以
const phases_dict = {
[Event.CAPTURING_PHASE]: 'Capturing Phase',
[Event.AT_TARGET]: 'Target Phase',
[Event.BUBBLING_PHASE]: 'Bubbling Phase'
};
// First listener defined without capturing flag, will fire first anyway
window.addEventListener( 'blur', evt => {
const current_phase = phases_dict[ evt.eventPhase ];
console.log( 'bubble blur is in', current_phase );
}, { capture: false } ); // fire at bubbling phase
// Second listener with capturing flag
window.addEventListener( 'blur', evt => {
// This one will also capture the events on Elements in the Document
// For our case, we only want the one on Window
if( evt.currentTarget === evt.target ) {
const current_phase = phases_dict[ evt.eventPhase ];
console.log( 'capture blur is in', current_phase );
}
}, { capture: true } ); // fire at capturing phase
// To show that bubbling events work as intended
// We also register click events
window.addEventListener( 'click', evt => {
const current_phase = phases_dict[ evt.eventPhase ];
console.log( 'bubble click is in', current_phase );
}, { capture: false } ); // fire at bubbling phase
window.addEventListener( 'click', evt => {
const current_phase = phases_dict[ evt.eventPhase ];
console.log( 'capture click is in', current_phase );
}, { capture: true } ); // fire at capturing phase
<pre>Click anywhere in this frame then click somewhere else in SO's page to trigger focus event</pre>
请注意,您可以停止 Elements 的传播。 模糊事件,但不模糊Window事件。
您必须找到其他方法来阻止当前的侦听器,也许是使用标志变量?
- 1 回答
- 0 关注
- 84 浏览
添加回答
举报