Js事件流

来自CloudWiki
跳转至: 导航搜索

事件流: 分三个阶段:捕获,目标,冒泡 目标阶段:目标元素就是事件源,事件源上的捕获和冒泡是谁写在前面就先执行谁。事件源上的事件是按顺序执行的。 冒泡 概念: 对于相互嵌套的元素,从结构上(非视觉上)从点击的元素开始向上查找是否存在相同的事件(不是所有的事件),如果存在,就会发生冒泡 捕获: 概念: 对于相互嵌套的元素,从结构上(非视觉上)从顶端的元素开始向下查找是否存在相同的事件(不是所有的事件),直到点击的元素为止,如果存在,就会发生捕获 IE上没有 事件委托: 概念:通过给一个元素添加事件,来管理一类元素的事件。 原理: 1.利用了冒泡事件的原理 2.利用了事件源来查找当前点击的对象 优势: 1.提高效率 e=e||window.event; 阻止冒泡 W3C:e.stopPropagation() IE9及IE9以上 ie :e.cancelBubble=true; 谷歌已经实现 封装阻止冒泡的兼容方法 阻止默认事件:一般用于a标签和表单提交 return false; e.preventDefault(); //IE9及IE9以上 e.returnValue=true;//IE独有 封装阻止默认事件方法: -->

<!DOCTYPE html> <html> <head> <title>事件流</title> <meta charset="utf-8">

<style>
       .box{
           width:300px;
           height:300px;
           padding:40px;
           background-color:red;
       }
       .con{
           padding:40px;
           background-color:blue;
       }
       p{
           padding:40px;
           background-color:orange;
       }
       span{
           display: block;
           padding:40px;
           background-color:green;
       }
   </style> 

</head> <body>

<a href="javascript:void(0)">百度</a>
<a href="http://www.qq.com" >腾讯</a>

<script>
   var box=document.getElementsByClassName("box")[0];
   var con=document.getElementsByClassName("con")[0];
   var list=document.getElementsByClassName("list")[0];
   var p=document.getElementsByTagName("p")[0];
   var span=document.getElementsByTagName("span")[0];


   box.addEventListener("click",function(){
       console.log("Mred");
   })
   con.addEventListener('click',function(){
       console.log("Mgreen");
   })
   list.addEventListener('click',function(){
       console.log("Mblue");
   })
   p.addEventListener('click',function(){
       console.log("Mpink");
   })
   span.addEventListener('click',function(){
       console.log("M#fff");
   })
   // document.addEventListener('click',function(){
   //     console.log("M-document");
   // })


   box.addEventListener("click",function(){
       console.log("Bred");
   }, true)
   con.addEventListener('click',function(){
       console.log("Bgreen");
   },true)
   list.addEventListener('click',function(){
       console.log("Bblue");
   },true)
   p.addEventListener('click',function(){
       console.log("Bpink");
   },true)
   span.addEventListener('click',function(){
       console.log("B#fff");
   },true)
   // document.addEventListener('click',function(){
   //     console.log("B-document");
   // },true)

</script>


<script> // function test(a){ // var e=window.event||arguments.callee.caller.arguments[0]; // e.preventDefault(); // a.style.backgroundColor="red"; // } // // // var tenxun=document.getElementsByTagName("a")[1]; // tenxun.onclick=function(e){ // e=e||window.event; // e.preventDefault(); // // e.returnValue=true; // this.style.backgroundColor="red"; // // return false;

// }

// function cancelDefault(e){ // if(e.preventDefault){ // return e.preventDefault(); // }else{ // return e.returnValue=true; // } // } </script> </body> </html> 百度 腾讯