事件的传播

  1 <!DOCTYPE html>
  2 <html>
  3 <head>
  4     <meta charset="UTF-8">
  5     <title></title>
  6 </head>
  7 <script type="text/javascript">
  8 
  9 window.onload=function()
 10 {
 11 var box1=document.getElementById("box1");
 12 var box2=document.getElementById("box2");
 13 var box3=document.getElementById("box3");
 14 /*
 15 事件的传播
 16 关于事件的传播网景公司和微软公司有不同的理解
 17 微软公司
 18 认为事件应该是由内向外传播,也就是当事件触发时,应该先触发当前元素上的事件,
 19 然后再向当前元素的祖先元素上传播,也就是事件应该在冒泡的阶段执行
 20 网景公司
 21 认为事件应该是由外向内传播的,也就是当前事件触发时,应该先触发当前元素的最外层的祖先元素的事件
 22 W3C综合了两个公司的方案,将事件传播分成了三个阶段
 23 1.捕获阶段
 24   在捕获阶段时从最外层的祖先元素,向目标元素进行事件的捕获,但是默认此时不会触发事件
 25 2.目标阶段
 26   事件捕获到目标元素,捕获结束,开始在目标元素上触发事件
 27 3.冒泡阶段
 28   事件从目标元素向祖先元素传递,分别依次触发祖先元素上的事件
 29 
 30 如果希望在捕获阶段就触发事件,可以将addEventLietener()的第三个参数设置为true
 31 一般情况下,我们不希望在捕获阶段触发事件,所以这个参数一般都是false
 32 注意在IE8以下的浏览器中没有捕获阶段
 33 
 34 bind(box1,"click",function(){
 35 alert("box1");
 36 });
 37 bind(box2,"click",function(){
 38 alert("box2");
 39 });
 40 bind(box3,"click",function(){
 41 alert("box3");
 42 });
 43 */
 44 bind2(box2,"click",function(){
 45 alert("box2 true");
 46 })
 47 bind2(box1,"click",function(){
 48 alert("box1 true");
 49 });
 50 bind2(box3,"click",function(){
 51 alert("box3 true");
 52 });
 53 };
 54 
 55 function bind(obj,eventStr,callback){
 56 if(obj.addEventListener){
 57  obj.addEventListener(eventStr,callback,false);
 58 }
 59 else{
 60  obj.attachEvent("on"+eventStr,function(){
 61  callback.call(obj);
 62  });
 63 }
 64 }
 65 
 66 function bind2(obj,eventStr,callback){
 67 if(obj.addEventListener){
 68 obj.addEventListener(eventStr,callback,true);
 69 }
 70 else{
 71 obj.attachEvent("on"+eventStr,function(){
 72 callback.call(obj);
 73 });
 74 }
 75 }
 76 
 77   </script>
 78 <style type="text/css">
 79     #box1{
 80     width:300px;
 81     height:300px;
 82     background-color:yellowgreen;
 83     }
 84     #box2{
 85     width:200px;
 86     height:200px;
 87     background-color:yellow;
 88     }
 89     #box3{
 90     width:150px;
 91     height:150px;
 92     background-color:skyblue;
 93     }
 94 </style>
 95 <body>
 96 <div id="box1">
 97     <div id="box2">
 98         <div id="box3"></div>
 99     </div>
100 </div>
101 </body>
102 </html>
原文地址:https://www.cnblogs.com/zuiaimiusi/p/11259554.html