由于各个浏览器中原生事件对象的 差异性 ,多数 JS库/框架 都或多或少的对原生事件对象进行了修复及包装。
比如,停止事件冒泡IE用 cancelBubble ,标准浏览器则用 stopPropagation 。
获取事件源对象,IE用 srcElement ,标准浏览器则用 target 诸如此类。
jQuery 对原生事件对象的修复和包装主要使用 jQuery.Event 类和 jQuery.event.fix 方法。
view sourceprint 01 jQuery.Event = function( src ) {
02 // Allow instantiation without the new keyword
03 if ( !this.preventDefault ) {
04 return new jQuery.Event( src );
05 }
06
07 // Event object
08 if ( src && src.type ) {
09 this.originalEvent = src;
10 this.type = src.type;
11
12 // Events bubbling up the document may have been marked as prevented
13 // by a handler lower down the tree; reflect the correct value.
14 this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
15 src.getPreventDefault && src.getPreventDefault()) returnTrue : returnFalse;
16
17 // Event type
18 } else {
19 this.type = src;
20 }
21
22 // timeStamp is buggy for some events on Firefox(#3843)
23 // So we wont rely on the native value
24 this.timeStamp = jQuery.now();
25
26 // Mark it as fixed
27 this[ jQuery.expando ] = true;
28 };
29
30 function returnFalse() {
31 return false;
32 }
33 function returnTrue() {
34 return true;
35 }
36
37 // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
38 // html">http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
39 jQuery.Event.prototype = {
40 preventDefault: function() {
41 this.isDefaultPrevented = returnTrue;
42
43 var e = this.originalEvent;
44 if ( !e ) {
45 return;
46 }
47
48 // if preventDefault exists run it on the original event
49 if ( e.preventDefault ) {
50 e.preventDefault();
51
52 // otherwise set the returnValue property of the original event to false (IE)
53 } else {
54 e.returnValue = false;
55 }
56 },
57 stopPropagation: function() {
58 this.isPropagationStopped = returnTrue;
59
60 var e = this.originalEvent;
61 if ( !e ) {
62 return;
63 }
64 // if stopPropagation exists run it on the original event
65 if ( e.stopPropagation ) {
66 e.stopPropagation();
67 }
68 // otherwise set the cancelBubble property of the original event to true (IE)
69 e.cancelBubble = true;
70 },
71 stopImmediatePropagation: function() {
72 this.isImmediatePropagationStopped = returnTrue;
73 this.stopPropagation();
74 },
75 isDefaultPrevented: returnFalse,
76 isPropagationStopped: returnFalse,
77 isImmediatePropagationStopped: returnFalse
78 };
jQuery.Event 类主要做了以下工作
1,扩充了 originalEvent 属性,该属性暂存了原生事件对象。
2,修复了 timeStamp ,该属性IE6/7/8不支持,其它支持的各个浏览器中返回值也不同。
3,阻止DOM元素默认行为统一采用 preventDefault
4,停止事件冒泡统一采用 stopPropagation
5,实现或扩充了 DOM3事件 的几个方法:stopImmediatePropagation、isDefaultPrevented、isPropagationStopped、isImmediatePropagationStopped
此外,jQuery.Event的 写类方式 也较独特。它 使用隐藏的new创建对象 。
jQuery.event.fix方法 如下
view sourceprint 01 fix: function( event ) {
02 if ( event[ jQuery.expando ] )