事件捕获 & 事件冒泡
<body> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> </body> <script> window.onload = function() { var oDiv1 = document.getElementById('div1'); var oDiv2 = document.getElementById('div2'); var oDiv3 = document.getElementById('div3'); function fn1() { alert( this.id ); } /*oDiv1.onclick = fn1; oDiv2.onclick = fn1; oDiv3.onclick = fn1;*/ //false = 冒泡(出去) true = 捕获(进来) //告诉div1,如果有一个出去的事件触发了你,你就去执行fn1这个函数 /*oDiv1.addEventListener('click', fn1, false); oDiv2.addEventListener('click', fn1, false); oDiv3.addEventListener('click', fn1, false);*/ //告诉div1,如果有一个进来的事件触发了你,你就去执行fn1这个函数 /*oDiv1.addEventListener('click', fn1, true); oDiv2.addEventListener('click', fn1, true); oDiv3.addEventListener('click', fn1, true);*/ oDiv1.addEventListener('click', function() { alert(1); }, false); oDiv1.addEventListener('click', function() { alert(3); }, true); oDiv3.addEventListener('click', function() { alert(2); }, false); //3 2 1 } </script>
下拉菜单--取消冒泡案例:
<style> div { width: 200px; height: 200px; background-color: red; display: none; } </style> <script> window.onload = function () { var oBtn = document.getElementsByTagName('button')[0]; var oDiv = document.getElementsByTagName('div')[0]; oBtn.onclick = function (ev) { var oEvent = ev || event; //取消冒泡,让事件不再往上面传递 oEvent.cancelBubble = true; oDiv.style.display = 'block'; } document.onclick = function () { oDiv.style.display = 'none'; } } </script> <body> <button>显示</button> <div></div> </body>