This article mainly introduces cross-browser JavaScript event processing, aiming at full-browser compatibility. For more information, see
1. Obtain event objects
FF is a little stubborn. It only supports arguments [0] and does not support window. event. This time, I really don't blame IE. Although the event as the window attribute is not standardized, everyone has already acquiesced in this small problem. FF has been a maverick for so many years. Therefore, the cross-browser event object can be obtained in the following two ways:
Parameters:
GetEvent: function (event) {return event? Event: window. event; // return event | window. event; // or a simpler method}
No parameter:
Function getEvent () {return arguments [0]? Arguments [0]: window. event; // return arguments [0] | window. event; // or a simpler method}
In particular, one method is required: HTML DOM0-level mode + Event processor with parameters, as shown below:
Function handler (event) {// do something}
Button
The above method is compatible with all browsers, but the disadvantages of the DOM0-level method that relies on HTML are obvious, so it has not become a mainstream method like the first two, JS's DOM0-level mode + Event processor with parameters are as follows:
Function handler (event) {// do something} btn. onclick = handler; // JS DOM0-level method // btn. onclick = function (event) {/* do something */} // or an anonymous function with the same effect
This method is not compatible with all browsers. It is not supported by [IE8-]. IE9 + unknown, FF, and Chrome support. I always thought that HTML DOM0-level event processing is equivalent to JS DOM0-level event processing. Now I have done a lot of experiments to find that the two are different.
Ii. Obtain event sources
Event.srcelementis the only formula for Internet Explorer. ie9's unknown, and its browser supports the standard event.tar get method.
3. Block default event Behavior
Event. preventDefault () is a standard method, but [IE8-] is not supported. The IE Method is event. returnValue = false;
Iv. Stop event Propagation
Event. stopPropagation () is a standard method, and IE has another opinion. He wants to play like this: event. cancelBubble = true; special attention should be paid here, because cancel is an attribute rather than a method, which is far from the standard and is easy to remember.
5. add and remove event Processors
DOM0-level Mode
Ele. onclick = handler; ele. onclick = null; the oldest way
Advantage: Full browser compatibility
Disadvantage: Only one event processor can be bound to or unbound from the same event.
DOM2 level
ele.add/removeEventListener(eventType, handler, catch);
And IE: ele. attach/detachEvent ('on' + eventType, handler );
Advantage: supports binding/unbinding multiple event Processors
Disadvantage: Compatibility judgment is required. Note that the last parameter in the standard mode indicates whether to bind/unbind In the event capture phase. IE does not support event capture, so there is no third parameter.
Note: in IE mode, not only method names and standards are different, but also on must be added to the event type in the parameter. Otherwise, the binding is invalid but no error is reported.
6. cross-browser event handling
// Cross-browser event processor addition method var EventUtil = {addHandler: function (elem, type, handler) {if (elem. addEventListener) {elem. addEventListener (type, handler, false);} else if (elem. attachEvent) {elem. attachEvent ("on" + type, handler); // when you add multiple handler of the same type, the rule in IE mode is the first trigger last added} else {if (typeof elem ["on" + type] = 'function ') {var oldHandler = elem ["on" + type]; elem ["on" + type] = function () {oldHandler (); handler ();} Else {elem ["on" + type] = handler; // multiple event processors can be added. }}, getEvent: function (event) {return event? Event: window. event;}, getTarget: function (event) {return event.tar get | event. srcElement;}, preventDefault: function (event) {if (event. preventDefault) {event. preventDefault ();} else {event. returnValue = false ;}}, removeHandler: function (elem, type, handler) {if (elem. removeEventListener) {elem. removeEventListener (type, handler, false);} else if (elem. detachEvent) {elem. detachEvent ("on" + type, handler);} else {elem ["on" + type] = null; // the removal of a single event processor is not supported. Only all event processors can be removed }}, stopPropagation: function (event) {if (event. stopPropagation) {event. stopPropagation ();} else {event. cancelBubble = true ;}}, getRelatedTarget: function (event) {if (event. relatedTarget) {return event. relatedTarget;} else if (event. toElement & event. type = "mouseout") {return event. toElement;} else if (event. fromElement & event. type = "mouseover") {return event. fromElement;} else {return null ;},/* the left and middle buttons of IE8 are both 0; FF cannot recognize the middle keys; Chrome is normal */getButton: function (event) {// return 0, 1, 2-left, center, right if (document. implementation. hasFeature ("MouseEvents", "2.0") {return event. button;} else {switch (event. button) {case 0: case 1: case 3: case 5: case 7: return 0; break; case 2: case 6: return 2; break; case 4: return 1; break; default: break ;}},/* can only detect keypress events. the return value is equal to the character encoding to be displayed * // * IE and Chrome are triggered only by the character key that can be displayed, other FF keys can also be triggered. The returned value is 0 */getCharCode: function (event) {if (typeof event. charCode = "number") {return event. charCode;} else {return event. keyCode ;}}};
Comprehensive example
If libraries such as jQuery are not used in the project, how can we easily bind events to elements and be compatible with various browsers? The following simple Utility should be considered.
var eventUtility = { addEvent : function(el, type, fn) { if(typeof addEventListener !== "undefined") { el.addEventListener(type, fn, false); } else if(typeof attachEvent !== "undefined") { el.attachEvent("on" + type, fn); } else { el["on" + type] = fn; } }, removeEvent : function(el, type, fn) { if(typeof removeEventListener !== "undefined") { el.removeEventListener(type, fn, false); } else if(typeof detachEvent !== "undefined") { el.detachEvent("on" + type, fn); } else { el["on" + type] = null; } }, getTarget : function(event) { if(typeof event.target !== "undefined") { return event.target; } else { return event.srcElement; } }, preventDefault : function(event) { if(typeof event.preventDefault !== "undefined") { event.preventDefault(); } else { event.returnValue = false; } }};
Example:
var eventHandler = function(evt) { var target = eventUtility.getTarget(evt), tagName = target.tagName; if(evt.type === "click") { if(tagName === "A" || tagName === "BUTTON") { alert("You clicked on an A element, and the innerHTML is " + target.innerHTML + "!"); eventUtility.preventDefault(evt); } } else if(evt.type === "mouseover" && tagName === "A") { alert("mouseovered " + target.innerHTML); }};eventUtility.addEvent(document, "click", eventHandler);eventUtility.addEvent(document, "mouseover", eventHandler);eventUtility.removeEvent(document, "mouseover", eventHandler);