This article describes how to add and remove event encapsulation compatible with various browsers implemented by pure JavaScript. This article provides the implementation code directly, with detailed comments in the code. For more information, see
// Event processing is compatible with various browsers and uses the capability detection method. The so-called capability detection means that an object capable of event processing is not implemented if it is not capable. // It is compatible with various browsers, dom2-level event processing and ie events. if both events are incompatible, use dom0-level var eventUtil = {addEvent: function (element, type, handler) {if (element. addEventListener) {// non-IE browser uses dom2-level event processing, type is the event type such as click, handler is the event processing function, and false indicates that the event uses the bubble processing model, if it is true, the capture processing model is used. // except for netbeans, the capture processing model is used. Otherwise, the bubble processing model is used. // if a non-IE browser adds an event as addEventListener element. addEventListener (type, handler, false );} Else if (element. attachEvent) {// if it is an IE browser, add the event using attachEvent element. attachEvent ('on' + type, handler);} else {element ['on' + type] = handler ;}}, removeEvent: function (element, type, handler) {if (element. removeEventListener) {// non-IE browser uses dom2-level event processing, type is the event type such as click, handler is the event processing function, and false indicates that the event uses the bubble processing model, if it is true, the capture processing model is used. // except for netbeans, the capture processing model is used. Otherwise, the bubble processing model is used. // if the event is added to a non-IE browser, the removeEventListener element is used. remove EventListener (type, handler, false);} else if (element. detachEvent) {// if it is an IE browser, the event is added using the detachEvent element. detachEvent ('on' + type, handler);} else {// dom0-level event processing, if the delete event is assigned null element ['on' + type] = null ;}}, getEvent: function (event) {// get the return event of the event itself? Event: window. event;}, getType: function (event) {// get the event type return event. type ;}, getElement: function (event) {// gets the event action element return event.tar get | event. srcElement;}, preventDefault: function (event) {// block default event behavior if (event. preventDefault) {event. preventDefault ();} else {event. returnValue = false ;}}, stopProPagation: function (event) {// stop event bubbling if (event. stopProPagation) {event. stopProPagation ();} else {event. cancelBubble = true ;}}}