一, 基本概念: DOM 事件的级别
解答:
- DOM0 element.onclick=function(){}
- DOM2 element.addEventListener('click',function(){},false)
- DOM3 element.addEventListener('keyup',function(){},false)
ps: 捕获阶段是 true; 冒泡阶段是 false;
解答: 捕获 (从上往下) 冒泡 (从下往上)
三, DOM 事件流
解答:
第一阶段: 捕获
第二阶段: 目标阶段
第三阶段: 冒泡
四, 描述 DOM 事件的捕获的具体流程
解答:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Event</title>
- <style type="text/CSS">
- #ev{width: 300px;height: 100px;background: purple;color: #fff;text-align: center;line-height: 100px;}
- </style>
- </head>
- <body>
- <div id="ev"> 目标元素 </div>
- <script type="text/javascript">
- var ev=document.getElementById('ev');
- window.addEventListener('click',function(){
- console.log('window captrue');
- },true);
- document.addEventListener('click',function(){
- console.log('document captrue');
- },true);
- document.documentElement.addEventListener('click',function(){
- console.log('html captrue');
- },true);
- document.body.addEventListener('click',function(){
- console.log('body captrue');
- },true);
- ev.addEventListener('click',function(){
- console.log('ev captrue');
- },true);
- </script>
- </body>
- </html>
捕获流程和定义的顺序没关系 (调换定义顺序也没影响), 是和他响应的顺序有关系; 冒泡流程把 true 改为 false 就是冒泡的了;
五, Event 对象的常见应用
解答:
1,event.preventDefault() ----- 阻止默认事件 (如 a 链接的默认跳转)
2,event.stopPropagation() ----- 阻止冒泡行为
3,event.stoplmmediatePropagation() ----- 事件响应优先级的时候会用到
4,event.currentTarget ----- 当前被绑定的事件对象
5,event.target ----- 当前被点击的元素
六, 自定义事件
解答:
- var eve=new Event('custome');
- ev.addEventListener('custome',function(){
- console.log('custome');
- });
- ev.dispatchEvent(eve);
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Event</title>
- <style type="text/css">
- #ev{width: 300px;height: 100px;background: purple;color: #fff;text-align: center;line-height: 100px;}
- </style>
- </head>
- <body>
- <div id="ev"> 目标元素 </div>
- <script type="text/javascript">
- var ev=document.getElementById('ev');
- // 自定义事件
- var eve=new Event('test');
- ev.addEventListener('test',function(){
- console.log('test dispatch');
- });
- ev.dispatchEvent(eve);
- </script>
- </body>
- </html>
来源: http://www.qdfuns.com/article/12560/88ee0b9296fb9d816186cabe85fde079.html