javascript DOM事件总结

时间:2022-12-05 14:37:40
 1 <html>
2 <title>事件</title>
3 <meta charset="utf-8"/>
4 <body>
5 <div id="box">
6 <input type="button" value="按钮" id="btn" onclick="showMes()"/>
7 <input type="button" value="按钮2" id="btn2"/>
8 <input type="button" value="按钮3" id="btn3"/>
9 <a href="event.html" id="go" target="_blank">跳转</a>
10 </div>
11 </body>
12 </html>
13 <script>
14 /**
15 * 非IE
16 * event.type 获取事件的类型
17 * event.target属性 获取事件的目标
18 * event.stopPropagation()方法;//阻止事件冒泡
19 * event.preventDefault()方法;//阻止事件默认行为
20 *
21 * IE
22 * event.type 获取事件的类型
23 * event.srcElement
24 * event.cancelBubble属性阻止事件冒泡
25 * 设置为true为阻止冒泡,设置为false不阻止冒泡
26 * returnValue=false 阻止事件默认行为
27 *
28 */
29 function showMes(event){
30 event = event || window.event;
31 var ele = event.target || event.srcElement;
32 alert(ele.nodeName);
33 }
34
35 function showbox(){
36 alert('这里放盒子');
37 }
38
39 function stopGoto(event){
40 //event.type 获取事件的类型
41 //event.target属性 获取事件的目标
42 event.stopPropagation();//阻止事件冒泡
43 event.preventDefault();//阻止事件默认行为
44 }
45
46 var btn2 = document.getElementById("btn2");
47 var btn3 = document.getElementById("btn3");
48 var go = document.getElementById("go");
49 btn2.onclick = function(){
50 alert('通过DOM0级添加事件');
51 }
52 btn2.onclick = null;
53
54 //DOM2级事件
55 var eventUtil = {
56
57 //添加句柄
58 addHandler:function(element,type,handler){
59 if(element.addEventListener){
60 element.addEventListener(type,handler,false);
61 }else if(element.attachEvent){
62 element.attachEvent('on'+type,handler);
63 }else{
64 element['on'+type] = handler;
65 }
66 },
67 //删除句柄
68 removeHandler:function(element,type,handler){
69 if(element.removeEventListener){
70 element.removeEventListener(type,handler,false);
71 }else if(element.detachEvent){
72 element.detachEvent('on'+type,handler);
73 }else{
74 element['on'+type] = null;
75 }
76 },
77
78 getEvent:function(event){
79 return event ? event : window.event;
80 },
81
82 getElement:function(event){
83 return event.target || event.srcElement;
84 },
85
86 preventDefault:function(event){
87 if(event.preventDefault){
88 event.preventDefault();
89 }else{
90 event.returnValue = false;
91 }
92 },
93
94 stopPropagation:function(event){
95 if(event.stopPropagation){
96 event.stopPropagation();
97 }else{
98 event.cancelBubble = true;
99 }
100 }
101 };
102
103 eventUtil.addHandler(btn3,"click",showMes);
104 //eventUtil.removeHandler(btn3,"click",showMes);
105 eventUtil.addHandler(box,"click",showbox);
106 eventUtil.addHandler(go,"click",stopGoto);
107 </script>