以前一直以为cancelBubble是IE8及以下的专属,今天做一个测试的时候意外发现了所有浏览器都支持,便提出来希望有哪位解释下。
<p id="wq">
<span id="we">click</span>
</p>
1.使用原生js在FF下和chrome下两种方法都可以阻止冒泡
document.getElementById("wq").addEventListener("click",function(e){
console.log('wq');
},false);
document.getElementById("we").addEventListener("click",function(e){
console.log(e);
// e.stopPropagation();
e.cancelBubble = true;
},false);
2使用jquery两种方法也都可以阻止冒泡
$("#wq").on("click",function(){
console.log("wq");
});
$("#we").on("click",function(e){
console.log(e);
// e.stopPropagation();
e.originalEvent.cancelBubble = true;
})
PHPz2017-04-10 15:32:56
虽然说cancelBubble
可以在Chrome和Firefox中阻止冒泡,那是因为人家Chrome,Firefox 考虑周到,提供了这么一种可选的方式。 但是,cancelBubble
已经不在标准中了,相信迟到它们会移除这一特性的,所以,为了靠谱起见,还是乖乖地该怎么用怎么用吧。
另外,jquery
的stopPropagation()
已经做了兼容性处理:
jQuery.Event.prototype = {
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
}
}