标签:
在说事件冒泡之前,我们先说说事件对象(Event)
/* 封装Event对象 IE:window.event */ function getEvent(event){ return event?event:window.event; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>事件冒泡</title> <meta name="description" content=""> <meta name="keywords" content=""> <link href="" rel="stylesheet"> <style> .one{ width:400px; height:100px; border:1px solid #333; } .two{ height:35px; line-height:35px; padding-left:15px; border:1px solid red; } .three{ padding:10px; background-color: green; border:1px solid #999; cursor:pointer; } </style> <script src = "http://code.jquery.com/jquery-1.11.2.min.js"></script> <script> $(function(){ $(".one").click(function(event) { alert($(this).text()); }); $(".two").click(function(event) { alert($(this).text()); }); $(".three").click(function(event) { alert($(this).text()); }); }); </script> </head> <body> <div class="one"> 我是one(div) <p class="two"> 我是two(p) <span class="three">我是three(span)</span> </p> </div> </body> </html>
当在span、p、div元素上各绑定一个click事件,当单击span元素时,会依次触发三个事件,即span、p、div元素上的click事件,这就是事件冒泡,按照DOM层次结构像水泡一样不断向上直至顶端
/* 封装事件冒泡函数: document.all:判断浏览器是否是IE IE:cancelBubble Firefox:stopPropagation */ function stopPropagation(e){ var e = window.event || e; if(document.all){ e.cancelBubble = true; }else{ e.stopPropagation(); } }
/* 封装阻止元素的默认行为函数 IE:returnValue DOM:preventDefault */ function preventDefaultAction(event){ var event = window.event || event; if(document.all){ //支持IE event.returnValue = false; }else{ //IE不支持 event.preventDefault(); } }
标签:
原文地址:http://www.cnblogs.com/Essence/p/4266618.html