cancelBubble 和 stopPropagation 有什么区别?
谁能告诉我 Javascript 中使用 cancelBubble
和 stopPropagation
方法的区别。
Can anyone please tell me difference in usage of cancelBubble
and stopPropagation
methods used in Javascript.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
cancelBubble
是 IE 独有的布尔属性(不是方法),其作用与其他浏览器的stopPropagation()
方法相同,即阻止事件移动到它的下一个目标(当事件从内部元素传播到外部元素时称为“冒泡”,这是事件在 IE < 9 中传播的唯一方式)。 IE 9 现在支持stopPropagation()
,因此cancelBubble
最终将被淘汰。同时,以下是一个用于停止事件传播的跨浏览器函数:在事件处理函数中,您可以按如下方式使用它:
cancelBubble
is an IE-only Boolean property (not method) that serves the same purpose as thestopPropagation()
method of other browsers, which is to prevent the event from moving to its next target (known as "bubbling" when the event is travelling from inner to outer elements, which is the only way an event travels in IE < 9). IE 9 now supportsstopPropagation()
socancelBubble
will eventually become obsolete. In the meantime, the following is a cross-browser function to stop an event propagating:In an event handler function, you could use it as follows:
为了与 IE8 及更早版本兼容,如果
.stopPropagation()
未定义,请使用.cancelBubble
:在 MSDN 中阅读相关内容:https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ff975961(v=vs.85)
For compatibility with IE8 and older use
.cancelBubble
if.stopPropagation()
is undefined:Read about in MSDN: https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ff975961(v=vs.85)
任何人描述的另一个区别是
e.cancelBubble
仅在冒泡阶段(当事件到达第一个冒泡元素时)停止其他元素的事件传播,而.preventDefault()
在捕获和冒泡阶段防止传播(立即针对传播中的下一个元素)。Another difference that anyone has described is that
e.cancelBubble
stops event propagation for the further elements only in bubbling phase (when event reaches the first bubbling element), while.preventDefault()
prevent propagation both in capturing and bubbling phase (immediately for the next element in propagation).