事件机制会经历三个阶段:
1.捕获阶段,
2.触发阶段,
3.冒泡阶段,
element.addEventListener(eventName,handler,useCapture);
注册事件时候有三个参数:[eventName(string),handler(function),useCapture(boolean)];
三个参数分别代表:事件名称,回调函数,执行时机
当useCapture==true的时候在捕获阶段执行,否则在冒泡阶段执行,
顺序 :捕获阶段由内到外,冒泡阶段由外到内。
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>event</title> <style> #outer{ text-align: center; width: 400px; height: 400px; background-color: #ccc; margin: 0 auto; } #middle{ width: 250px; height: 250px; background-color: #f00; margin: 0 auto; } #inner{ width: 100px; height: 100px; background-color: #0f0; margin: 0 auto; } </style> </head> <body> <div id='outer'> <span>outer</span> <div id='middle'> <span>middle</span> <div id='inner'> <span>inner</span> </div> </div> </div> <script> function $(element){ return document.getElementById(element); } function on(element,event_name,handler,use_capture){ if(addEventListener){ $(element).addEventListener(event_name,handler,use_capture); } else{ $(element).attachEvent('on'+event_name,handler); } } on("outer","click",o_click_c,true); on("middle","click",m_click_c,true); on("inner","click",i_click_c,true); on("outer","click",o_click_b,false); on("middle","click",m_click_b,false); on("inner","click",i_click_b,false); function o_click_c(){ console.log("outer_捕获"); alert("outer_捕获"); } function m_click_c(){ console.log("middle_捕获"); alert("middle_捕获"); } function i_click_c(){ console.log("inner_捕获"); alert("inner_捕获"); } function o_click_b(){ console.log("outer_冒泡"); alert("outer_冒泡"); } function m_click_b(){ console.log("middle_冒泡"); alert("middle_冒泡"); } function i_click_b(){ console.log("inner_冒泡"); alert("inner_冒泡"); } </script> </body> </html>
执行结果:
可以看出来 :设置为true的会优先执行,全部设置为true则最外面的先执行,同样设置为false的最里面的先执行
文章参考:https://www.cnblogs.com/alvinwei1024/p/4739344.html