关于DOM事件捕获和冒泡顺序问题?

DOM事件的顺序是按照
捕获-->元素-->冒泡
的顺序进行的,但是请看下面代码

https://img2.mukewang.com/5c83747f0001c0ec05120731.jpg

但执行结果却是这样的

https://img1.mukewang.com/5c837488000122cc08000439.jpg

为什么最内层的元素没有按照捕获--冒泡的顺序执行,而是按照事件注入的顺序执行的呢?


Qyouu
浏览 402回答 1
1回答

慕斯王

如果把事件的传递看做一个流,那么它应该是一个首尾闭合的环,捕获和冒泡各点半个圆。那么问题在于捕获和冒泡是针对被点击对象(btn)的祖先元素而言的,但是对象本身就比较有意思了。如果对象里面还有子元素,并且你点击到了它的子元素,那么事件会流过子元素,然后再流回来,这个时候,代码的表现是正常的。DOM如下:<div id="app">&nbsp; &nbsp; &nbsp; &nbsp; <span id="btn">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <b>测试</b>&nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; </div>如果被点击对象里面没有子元素了,那么事件在这里已经终结了,也就是说『捕获』和『冒泡』在这个元素在进行交接,这个时候就有意思了,这两个事件是同时触发的,那么 js 的监听代码的书写顺序会影响最后的 console 结果,如果这样写的话,那么代码就是按你的想法完成的:<body>&nbsp; &nbsp; <div id="app">&nbsp; &nbsp; &nbsp; &nbsp; <span id="btn">测试</span>&nbsp; &nbsp; </div><script>&nbsp; &nbsp; var btn = document.getElementById('btn');&nbsp; &nbsp; var app = document.getElementById('app');&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; //btn捕获&nbsp; &nbsp; btn.addEventListener('click',function(){&nbsp; &nbsp; &nbsp; &nbsp; console.log('捕获','btn');&nbsp; &nbsp; },true);&nbsp; &nbsp; //div捕获&nbsp; &nbsp; app.addEventListener('click',function(){&nbsp; &nbsp; &nbsp; &nbsp; console.log('捕获','div');&nbsp; &nbsp; },true);&nbsp; &nbsp; document.body.addEventListener('click',function(){&nbsp; &nbsp; &nbsp; &nbsp; console.log('捕获','body');&nbsp; &nbsp; },true);&nbsp; &nbsp; document.body.addEventListener('click',function(){&nbsp; &nbsp; &nbsp; &nbsp; console.log('冒泡','body');&nbsp; &nbsp; },false);&nbsp; &nbsp; //btn冒泡&nbsp; &nbsp; btn.addEventListener('click',function(){&nbsp; &nbsp; &nbsp; &nbsp; console.log('冒泡','btn');&nbsp; &nbsp; },false);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; //div冒泡&nbsp; &nbsp; app.addEventListener('click',function(){&nbsp; &nbsp; &nbsp; &nbsp; console.log('冒泡','div');&nbsp; &nbsp; },false);</script></body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript