The pure JavaScript implementation is compatible with add and remove event encapsulation for all browsers

  • 2020-05-19 04:13:42
  • OfStack


// Event processing compatible with a variety of browsers, the use of capability detection method, the so-called capability detection, is the ability to do, do not do not have the ability 
 
 // define 1 Two event-handling objects, compatible with various browsers, dom2 Level event handling and ie Event, if both events are incompatible, then use dom0 Level of processing 
 var eventUtil ={
    addEvent:function(element,type,handler){
      if (element.addEventListener) {
      	// non IE Browser adoption dom2 Level 1 event handling, type Is the event type, such as: click . handler Is the event handler function, false The bubble handling model is used to represent the event, if yes true On behalf of   The capture processing model is adopted 
      	// In addition to netbeans Capture processing model is adopted, and bubble processing model is adopted 
      	// If you are IE The browser added event is: addEventListener
      	element.addEventListener(type,handler,false);
      }else if (element.attachEvent) {
      	// If it is IE Browser, add the event to take  attachEvent
      	element.attachEvent('on'+type,handler);
      }else{
        element['on'+type] = handler;
      }
    },
    removeEvent:function(element,type,handler){
      if (element.removeEventListener) {
      	// non IE Browser adoption dom2 Level 1 event handling, type Is the event type, such as: click . handler Is the event handler function, false The bubble handling model is used to represent the event, if yes true On behalf of   The capture processing model is adopted 
      	// In addition to netbeans Capture processing model is adopted, and bubble processing model is adopted 
      	// If you are IE The browser added event is: removeEventListener
      	element.removeEventListener(type,handler,false);
      }else if (element.detachEvent) {
      	// If it is IE Browser, add the event to take  detachEvent
      	element.detachEvent('on'+type,handler);
      }else{
      	//dom0 Level event handling if the delete event is assigned null
        element['on'+type] = null;
      }
    },
    getEvent:function(event){
    	  // Get the event itself 
    	 return event?event:window.event;
    },
    getType:function(event){
    	 // Get the event type 
    	 return event.type;
    },
    getElement:function(event){
    	 // Gets the event action element 
    	 return event.target || event.srcElement;
    },
    preventDefault:function(event){
    	  // Block the default event behavior 
      if(event.preventDefault){
      	  event.preventDefault();
      }else{
      	  event.returnValue = false;
      }
    },
    stopProPagation:function(event){
    	// Stop the event bubbling 
    	  if(event.stopProPagation){
        event.stopProPagation();
    	  }else{
    	  	  event.cancelBubble = true;
    	  }
    }




 }

Related articles: