cari

Rumah  >  Soal Jawab  >  teks badan

javascript - 使用cancelBubble可以阻止所有浏览器的冒泡?

以前一直以为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;
  })
天蓬老师天蓬老师2896 hari yang lalu474

membalas semua(1)saya akan balas

  • PHPz

    PHPz2017-04-10 15:32:56

    虽然说cancelBubble可以在Chrome和Firefox中阻止冒泡,那是因为人家Chrome,Firefox 考虑周到,提供了这么一种可选的方式。 但是,cancelBubble已经不在标准中了,相信迟到它们会移除这一特性的,所以,为了靠谱起见,还是乖乖地该怎么用怎么用吧。
    另外,jquerystopPropagation()已经做了兼容性处理:

    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;
        }
    }
    

    balas
    0
  • Batalbalas