cancelBubble和stopPropagation有什么区别? [英] What's the difference between cancelBubble and stopPropagation?

查看:143
本文介绍了cancelBubble和stopPropagation有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我在javascript中使用的 cancelBubble stopPropagation 方法的区别。

Can anyone please tell me difference in usage of cancelBubble and stopPropagation methods used in javascript.

推荐答案

cancelBubble 是一个仅提供IE的布尔属性(非方法)用作其他浏览器的 stopPropagation()方法,用于防止事件移动到下一个目标(当事件从内部移动到另一个目标时称为冒泡外部元素,这是事件在IE中传播的唯一方式< 9)。 IE 9现在支持 stopPropagation()所以 cancelBubble 最终会过时。在此期间,以下是用于停止事件传播的跨浏览器函数:

cancelBubble is an IE-only Boolean property (not method) that serves the same purpose as the stopPropagation() 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 supports stopPropagation() so cancelBubble will eventually become obsolete. In the meantime, the following is a cross-browser function to stop an event propagating:

function stopPropagation(evt) {
    if (typeof evt.stopPropagation == "function") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
}

在事件处理函数中,您可以将其用作如下:

In an event handler function, you could use it as follows:

document.getElementById("foo").onclick = function(evt) {
    evt = evt || window.event; // For IE
    stopPropagation(evt);
};

这篇关于cancelBubble和stopPropagation有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆