🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>触发事件的三个阶段</title> <style type="text/css"> #div1 { width: 300px; height: 200px; background-color: red; } #div2 { width: 250px; height: 150px; background-color: green; } #div3 { width: 200px; height: 100px; background-color: blue; } div:hover { cursor: pointer; } pre { font-size: 16px; font-weight: 700; } </style> </head> <body> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> <pre> 事件共有三个阶段: 1.事件捕获阶段 :从外向内 2.事件目标阶段 :最开始选择的那个 3.事件冒泡阶段 : 从里向外 addEventListener(event, function, useCapture)中的useCaptrue就是设置捕获阶段或冒泡阶段的。 通过e.eventPhase这个属性可以知道当前的事件是什么阶段的: 如果这个属性的值是: 1---->捕获阶段 2---->目标阶段 3---->冒泡 一般默认都是冒泡阶段,很少用捕获阶段 冒泡阶段:从里向外 捕获阶段:从外向内 </pre> <script type="text/javascript"> document.getElementById("div1").onclick = function(e) { console.log(e.eventPhase); } document.getElementById("div1").onclick = function(e) { console.log(e.eventPhase); } document.getElementById("div1").onclick = function(e) { console.log(e.eventPhase); } </script> </body> </html> ```