ブラウザをまたぐ部分コードのパッケージについて
11875 ワード
このコードはjavascript高級プログラム設計(第三版)の上のイベント部分から抽出したものです.共有してください.級はその時自分でメモを作ります.後で使えるはずです.
1 var EventUtil = {
2 addHandler: function (element, type, handler) {//
3 if (element.addEventListener) {// IE
4 element.addEventListener(type, handler, false);
5 }
6 else if (element.attachEvent) {//IE
7 element.attachEvent("on" + type, handler);
8 }
9 else {//dom0
10 element["on" + type] = handler;
11 }
12 },
13 removeHandler: function (element, type, handler) {//
14 if (element.removeEventListener) {// IE
15 element.removeEventListener(type, handler, false);
16 }
17 else if (element.detachEvent) {//IE
18 element.detachEvent("on" + type, handler);
19 }
20 else {//dom0
21 element["on" + type] = null;
22 }
23 },
24 getEvent: function (event) {// event
25 return event ? event : window.event;
26 },
27 getTarget: function (event) {//
28 return event.target || event.srcElement;
29 },
30 preventDefault: function (event) {// (a href,radio,checkbox,)
31 if (event.preventDefault) {
32 event.preventDefault();
33 }
34 else {
35 event.returnValue = false;
36 }
37 },
38 stopPropagation: function (event) {// EventUtil , ,
39 if (event.stopPrapagation) {
40 event.stopPropagation();
41 }
42 else {
43 event.cancelBubble = true;
44 }
45 },
46 getRelatedTarget: function (event) {//
47 /*
48 div; div , div, body.
49 mouseover: , .
50 mouseout: , .
51 */
52 if (event.relatedTarget) { return event.relatedTarget; }
53 else if (event.toElement) { return event.toElement; }
54 else if (event.fromElement) { return event.fromElement; }
55 else { return null; }
56 },
57 getButton: function (event) {//
58 if (document.implementation.hasFeature("MouseEvents", "2.0")) { return event.button; }
59 else {
60 switch (event.button) {
61 case 0:
62 case 1:
63 case 3:
64 case 5:
65 case 7:
66 return 0;//
67 case 2:
68 case 6:
69 return 2;//
70 case 4:
71 return 1;//
72 }
73 }
74 }
75 };