大多数事件在所有浏览器中都会冒泡。但是,我知道在 Internet Explorer 中“提交”事件不会冒泡。还有哪些不冒泡的事件?
load
unload
scroll
(文档上的滚动事件必须冒泡到窗口)focus
blur
DOMNodeRemovedFromDocument
DOMNodeInsertedIntoDocument
loadstart
progress
error
abort
load
loadend
来自:https://en.wikipedia.org/wiki/DOM_events#Events
为了检查事件是否通过 DOM 树冒泡,您应该检查 bubbles
对象及其实例上可用的只读
Event
属性。
“Event 接口的 bubbles 只读属性指示事件是否通过 DOM 树向上冒泡。”
在下面的代码示例中,您可以检查如何仅在
capturing phase
期间从附加在 DOM 层次结构 (document.body) 较高位置的事件侦听器跟踪“焦点”事件,而不能在冒泡阶段跟踪该事件。另一方面,点击事件可以在两个方向上捕获(捕获+冒泡阶段)。
// Check if the click event bubbles:
document.querySelector("input").addEventListener("click", e =>{
console.log(`Does the ${e.type} event bubble?`, e.bubbles);
}, { once: true });
// Check if the focus event bubbles:
document.querySelector("input").addEventListener("focus", e =>{
console.log(`Does the ${e.type} event bubble?`, e.bubbles);
}, { once: true });
// Track focus event during the bubbling phase (at least trying to):
document.body.addEventListener("focus", e =>{
console.log(`Tracking ${e.type} event during bubbling phase.`);
});
// Track focus event during the capturing phase:
document.body.addEventListener("focus", e =>{
console.log(`Tracking ${e.type} event during capturing phase.`);
}, { capture: true })
// Track click event during the bubbling phase:
document.body.addEventListener("click", e =>{
console.log(`Tracking ${e.type} event during bubbling phase.`);
});
// Track click event during the capturing phase:
document.body.addEventListener("click", e =>{
console.log(`Tracking ${e.type} event during capturing phase.`);
}, { capture: true })
<input placeholder="Focus or click...">
特定于一个元素的任何事件都不会冒泡:焦点、模糊、加载、卸载、更改、重置、滚动、大多数 DOM 事件(DOMFocusIn、DOMFocusOut、DOMNodeRemoved 等)、mouseenter、mouseleave 等
除了其余答案之外,文档元素上的 load 事件会冒泡,但它会在 Document 对象处停止冒泡,并且不会传播到 Window 对象。仅当整个文档加载完成后,才会触发 Window 对象的加载事件。
焦点和模糊事件不会冒泡
当前接受的答案**是垃圾 - 一方面,更改事件确实会冒泡。
但是,不同的元素在不同的时间点火/冒泡。
例如,对于更改事件,这些控件在字段模糊之前不会触发更改事件:
虽然这些控件在更改后立即触发/冒泡更改事件:
请参阅 这个 StackOverflow 的其他答案,了解更多详细信息和演示。
注意:模糊事件不会冒泡 - 但 focusout 事件会冒泡,并且除了冒泡属性之外,它是完全相同的事件。
** 由用户578895于2011年4月7日3:22回答