JavaScript事件

关于JavaScript事件讲解得很全面的一篇文章:http://www.cnblogs.com/tugenhua0707/p/4501843.html

如下代码需要注意的一点是,除了getEvent方法外,其他方法在被调用时传给它的事件参数应该是兼容浏览器的事件参数,所以可先调用getEvent获得兼容性参数再传进去,或者先 event=event||window.event再传进去

 1 var EventUtil = {
 2     addHandler: function(element,type,handler) {
 3         if(element.addEventListener) {
 4             element.addEventListener(type,handler,false);
 5         }else if(element.attachEvent) {
 6             element.attachEvent("on"+type,handler);
 7         }else {
 8             element["on" +type] = handler;
 9         }
10     },
11     removeHandler: function(element,type,handler){
12         if(element.removeEventListener) {
13             element.removeEventListener(type,handler,false);
14         }else if(element.detachEvent) {
15             element.detachEvent("on"+type,handler);
16         }else {
17             element["on" +type] = null;
18         }
19     },
20     getEvent: function(event) {
21         return event ? event : window.event;
22     },
23     getTarget: function(event) {
24         return event.target || event.srcElement;
25     },
26     preventDefault: function(event){
27         if(event.preventDefault) {
28             event.preventDefault();
29         }else {
30             event.returnValue = false;
31         }
32     },
33     stopPropagation: function(event) {
34         if(event.stopPropagation) {
35             event.stopPropagation();
36         }else {
37             event.cancelBubble = true;
38         }
39     },
40     getRelatedTarget: function(event){
41         if (event.relatedTarget){
42             return event.relatedTarget;
43         } else if (event.toElement){
44             return event.toElement;
45         } else if (event.fromElement){
46             return event.fromElement;
47         } else {
48             return null;
49         }
50     },
51     getWheelDelta: function(event) {
52         if(event.wheelDelta) {
53             return event.wheelDelta;
54         }else {
55             return -event.detail * 40
56         }
57     },
58     getCharCode: function(event) {
59         if(typeof event.charCode == 'number') {
60             return event.charCode;
61         }else {
62             return event.keyCode;
63         }
64     }
65 };

 

posted @ 2015-05-16 17:02  March On  阅读(158)  评论(0编辑  收藏  举报
top last
Welcome user from
(since 2020.6.1)