[javascript]事件冒泡处理
<!DOCTYPE html> <html> <head> <style type="text/css"> #box1 { width: 400px; height: 400px; background: #ccc; } #box2 { width: 300px; height: 300px; background: #ddd; } #box3 { width: 200px; height: 200px; background: #eee; } </style> <script type="text/javascript"> function addEventListener(obj, f, type) { if (obj.addEventListener) { obj.addEventListener(type, f, false); } else { obj.attachEvent(‘on‘ + type, function(event) { f.call(obj, event); }); } } function stopPropagation(event) { if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } } window.onload = function() { var box1 = document.querySelector(‘#box1‘); var box2 = document.querySelector(‘#box2‘); var box3 = document.querySelector(‘#box3‘); addEventListener(box1, function(event) { stopPropagation(event); alert(‘box1‘); }, ‘click‘); addEventListener(box2, function(event) { stopPropagation(event); alert(‘box2‘); }, ‘click‘); addEventListener(box3, function(event) { stopPropagation(event); alert(‘box3‘); }, ‘click‘); } </script> </head> <body> <div id="box1"> <div id="box2"> <div id="box3"> </div> </div> </div> </body> </html>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。