<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #box1 { width: 300px; height: 300px; background-color: red; } #box2 { width: 200px; height: 200px; background-color: green; } #box3 { width: 100px; height: 100px; background-color: blue; } </style> </head> <body> <div id="box1"> <div id="box2"> <div id="box3"> </div> </div> </div> <script> // addEventListener 的第三个参数的作用 var box1 = document.getElementById('box1'); var box2 = document.getElementById('box2'); var box3 = document.getElementById('box3'); var array = [box1, box2, box3]; // addEventListener 的第三个参数为false的时候 : 事件冒泡 // addEventListener 的第三个参数为true的时候 : 事件捕获 // 事件的三个阶段: // 第一个阶段: 捕获阶段 // 第二个阶段: 执行当前点击的元素 // 第三个阶段: 冒泡阶段 // for (var i = 0; i < array.length; i++) { // array[i].addEventListener('click', function () { // console.log(this.id); // }, true); // } // document.body.addEventListener('click', function () { // console.log('body'); // }, true); // box.onclick 只有事件冒泡 // box.attachEvent // attachEvent只有两个参数, 只有事件冒泡 // box.attachEvent('onclick', function () { // }); for (var i = 0; i < array.length; i++) { var box = array[i]; box.onclick = function () { console.log(this.id); } } document.body.onclick = function () { console.log('body'); } document.onclick = function () { console.log('document'); } </script> </body> </html>
事件冒泡的作用:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <ul id="ul"> <li>西施</li> <li>貂蝉</li> <li>昭君</li> <li>凤姐</li> <li>芙蓉姐姐</li> </ul> <script> // 事件委托: 原理事件冒泡 var ul = document.getElementById('ul'); ul.onclick = function (e) { // e 事件参数(事件对象): 当事件发生的时候,可以获取一些和事件相关的数据 // 获取到当前点击的li // e.target 是真正触发事件的对象 // console.log(e.target); // 让当前点击的li高亮显示 e.target.style.backgroundColor = 'red'; } </script> </body> </html>