<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>bubble event</title> <style type="text/css"> body{margin:0;} #one{ width:500px; height:300px; background:rgb(255,0,0); } #two{ width:400px; height:260px; background:rgb(255,50,50); } #three{ width:300px; height:240px; background:rgb(255,100,100); } #four{ width:200px; height:200px; background:rgb(255,150,150); } </style> </head> <body> <div id='one'> <div id='two'> <div id='three'> <div id='four'> </div> </div> </div> </div> <script> var one = document.getElementById('one'); var two = document.getElementById('two'); var three = document.getElementById('three'); var four = document.getElementById('four'); var useCapture = true; //false爲冒泡獲取【目標元素先觸發】 true爲捕獲獲取【父級元素先觸發】 one.addEventListener('click', function() { console.log('one'); }, useCapture); two.addEventListener('click', function() { console.log('two'); }, useCapture); three.addEventListener('click', function() { console.log('three'); }, useCapture); four.addEventListener('click', function() { console.log('four'); }, useCapture); /* false 冒泡 點擊four div 輸出結果:four three two one true 捕獲 點擊four div 輸出結果: one two three four */ </script> </body> </html>
addEventListener第三個參數useCapture ,true時爲捕獲,false時爲冒泡css
冒泡從目標對象開始,向父級元素至window傳遞;捕獲從window底層逐級至目標對象傳遞!html