Introduction to JavaScript event objects

  • 2020-05-27 04:27:32
  • OfStack

An important aspect of the JavaScript events is that they have some relatively homogeneous features that can provide powerful capabilities for development;
The most convenient and powerful are event objects, which help you handle mouse events and keyboard strokes.
You can also modify the capture/bubble flow function for 1-type events.

1 event object


//  Of the event handler function 1 The standard features are : Event objects that are accessed in some way contain contextual information about the current event ;
//  Event handling by 3 parts : object . Event handler = function ;
  document.onclick = function(){
    alert('Lee');
  }
  // PS: Explanation of the above procedures :click said 1 Event types , Click on the ;
  // onclick: said 1 Property of an event handler or binding object ( Or event listeners );
  // document: said 1 Three bound objects , Used to trigger an element region ;
  // function(): Anonymous functions are functions that are executed , Used for post-trigger execution ;

//  In addition to using anonymous function methods as the function being executed , You can also set it as a separate function ;
  document.onclick = box;                //  Simply assign the function name , Without parentheses ;
  function box(){
    alert('Lee');
  }

// this Keywords and context 
//  in   object-oriented   We learned in that chapter : in 1 In the object , Because of the scope ,this It represents the object closest to it ;
  var input = document.getElementsByTagName('input')[0];
  input.onclick = function(){
    alert(this.value);                // HTMLInputElement,this said input object ;
  }

//  When an event is triggered , Will produce 1 Event objects , This object contains all the information about the event ;
//  Includes the element that causes the event / Type of event / And other information related to a particular event ;
//  The event object , we 1 As said as event object , This object is passed by the browser as a parameter through the function ;
//  First of all, , We have to verify that 1 Under the , Are there any arguments passed in the execution function , Whether you can get hidden parameters ;
  function box(){                   //  Ordinary empty parameter functions ;
    alert(arguments.length);            // 0; No parameters are passed ;
  }
  input.onclick = function(){             //  The execution function of the event binding ;
    alert(arguments.length);            // 1; get 1 Hidden parameters ;
  }
  // PS: Through the above two sets of functions , We found that , The execution function can be obtained by event binding 1 Hidden parameters ;
  //  instructions , The browser will assign it automatically 1 A parameter , So this parameter is essentially event object ;
  input.onclick = function(){
    alert(arguments[0]);              // MouseEvent, Mouse event object ;
  }

  //  This is a bit of a hassle , So the easy thing to do is , It can be obtained directly by receiving parameters ;
  input.onclick = function(evt){           //  accept event object ,
    alert(evt);                  // MouseEvent, Mouse event object ;
  }

  //  Directly receive event object , is W3C The practice of ,IE Does not support ,IE It defines itself 1 a event object , Directly in the window.event Access can be ;
  input.onclick = function(evt){
    var e = evt || window.event;
    alert(e);                   //  Implement cross-browser compatible fetching event object ;
  }

// the mouse button information and screen coordinates can be obtained through the event object;

2 mouse events
// mouse events are the most commonly used type 1 events in Web. After all, the mouse is still the most important positioning device.

1. Mouse button


//  Only when the main mouse button is clicked (1 Generally is the left mouse button ) Will trigger click The event , Therefore, it is not necessary to detect the button information ;
//  But for the mousedown and mouseup case , In its event The object is 1 a button attribute , Means press or release the button ;
      non IE(W3C) In the button attribute 
   value             instructions  
  0        Represents the main mouse button (1 Generally is the left mouse button );
  1        Represents the mouse button in the middle ( Mouse wheel button );
  2        Represents the secondary mouse button (1 It is usually the right mouse button );
    IE In the button attribute  
  1        Represents the main mouse button (1 Generally is the left mouse button );
  2        Represents the secondary mouse button (1 It is usually the right mouse button );
  4        Indicates that the mouse button in the middle has been pressed ;
//  Mouse button compatibility ;
  function getButton(evt){
    var e = evt || window.event;
    if(evt){                // Chrome Browser support W3C and IE standard ;
      return e.button;          //  Pay attention to the order of judgment ;
    }else if(window.event){
      switch(e.button){
        case 1:
          return 0;
        case 4:
          return 1;
        case 2:
          return 2;
      }
    }
  }
  document.onmouseup = function(evt){
    if(getButton(evt) == 0){
      alert(' Press the left mouse button !');
    }else if(getButton(evt) == 1){
      alert(' I hit the middle key ');
    }else if(getButton(evt) == 2){
      alert(' Right click !');
    }
  }

2. Visual area and screen coordinates


//  The event object provides two sets of properties to get the browser coordinates :
// 1 Groups are the coordinates of the visual area of a page ;
// 1 Groups are screen coordinates ;
     Coordinate attribute 
   attribute         instructions 
  clientX      Visual area X coordinates , The distance from the left border ;
  clientY      Visual area Y coordinates , Distance from the top border ;
  screenX      The screen area X coordinates , Distance from the left screen ;
  screenY      The screen area Y coordinates , Distance from the screen ;
  pageX       In the page X coordinates , The distance from the left border of the entire page ;
  pageY       In the page Y coordinates , The distance from the entire page border ;

//  Determines the mouse click position function ;
  document.onclick = function(evt){
    var e = evt || window.event;
    alert(e.clientX+','+e.clientY);
    alert(e.screenX+','+e.screenY);
    alert(e.pageX+','+e.pageY);
  }
  // PS: When the page is not scrolling ,pageX and pageY The value of and clientX and clientY The values are equal ;
  // IE8 Page coordinates on the event object are not supported below , But it can be calculated using client area coordinates and scrolling information ;
  //  That's when you need to use document.body( Mixed mode ) or document.documentElement( The standard model ) In the scrollTop and scrollLeft attribute ;
  // pageX and pageY Compatible with the function ;
  var div = document.getElementById('myDiv');
  addEventListener(div,'click',function(evt){
    var evt = event || window.event;
    var pageX = evt.pageX,
      pageY = evt.pageY;
    if(pageX === undefined){
      pageX = evt.clientX+(docuemnt.body.scrollLeft || document.documentElement.scrollLeft);
    }
    if(pageY === undefined){
      pageY = evt.clientY+(document.body.scrollTop || document.documentElement.srollTop);
    }
    alert(pageX+pageY);
  });

3. The modify button


//  sometimes , We need to use some keys on the keyboard to trigger with the mouse 1 Something special ;
//  The key for :Shift/Ctrl/Alt and Meat(Window Is in the Windows key , In the MAC Cmd key );
//  They are often used to modify mouse events and behavior , So it's called modify key ;
         Modify key properties 
   attribute           instructions  
  shiftKey       Judge if it is pressed Shift key ;
  ctrlKey        Judge if it is pressed ctrlKey key ;
  altKey        Judge if it is pressed alt key ;
  metaKey        Judge if it is pressed windows key ,IE Does not support ;

//  Judge key function ;
  function getKey(evt){
    var e = evt || window.event;
    var keys = [];
    if(e.shiftKey) keys.push('shift');    //  Determine if you are pressing at the same time shift key ;
    if(e.ctrlKey) keys.push('ctrl');
    if(e.altKey) keys.push('alt');
    return keys;
  }
  document.onclick = function(evt){
    alert(getKey(evt));             //  get 1 An array , May contain shift/ctrl/alt The value of the ;
  }

3. Keyboard events

Keyboard events are triggered when the user is using the keyboard.
The "DOM2 level event "initially defined the keyboard event and later deleted the corresponding content;
The original keyboard events are still used, but IE9 is the first to support "DOM3" keyboard events.

1. The key code


 //  In the event of a keydown and keyup When an event is ,event The object's keyCode The property will contain 1 A code , With the keyboard 1 You have a particular key ;
 //  Alphanumeric character set ,keyCode The value of the ASCII The codes for lowercase letters or Numbers are the same ; Case does not matter in letters ;
   document.onkeydown = function(evt){
     alert(evt.keyCode);
   }

2. Character encoding


// Firefox/Chrome/Safari the event Object support 1 a charCode attribute ;
//  This property only occurs when keypress The value is included in the event , And this value is the key that was pressed to represent the character ASII coding ;( Also contains buttons other than Numbers and letters );
//  At this time keyCode Usually equal to the 0 Or it could be the code of the key being pressed ;
// IE and Opear Is in the keyCode Is used to save characters ASCII coding ;
  function getCharCode(evt){
    var e = evt || window.event;
    if(typeof e.charCode == 'number'){
      return e.charCode;
    }else{
      return e.keyCode;
    }
  }
  document.onkeypress = function(evt){
    alert(getCharCode(evt));
  }
  // PS: You can use String.fromCharCode() will ASCII The encoding is converted to the actual character ;

4 W3C IE
// in the standard DOM event, the event object contains properties and methods related to the specific event in which it was created;

// the type of event triggered is not the same, and the available properties and methods are not the same.

Properties and methods of event objects in W3C
Property/method type read/write description
bubbles Boolean read only to indicate whether the event is bubbling;
cancelable Boolean read-only indicates whether the default behavior of the event can be canceled;
currentTarget Element reads only the element whose event handler is currently processing the event;
detail Integer reads only the details related to the event; (1 value generally used for roller information);
eventPhase Integer read-only call event handler phase :1 for capture phase,2 for processing target,3 for bubbling phase;
preventDefault() Function is the default behavior of the read-only cancel event; If the value of cancelable is true, you can use this method;
stopPropagation() Function read only the next step of the cancellation event to catch or bubble; If the value of bubbles is true, you can use this method;
The target of the target Element read-only event;
type String reads only the type of event that is triggered;
view AbstractView reads only abstract views associated with events; The window object equivalent to the event that occurred;

Properties of event objects in IE
Property type read/write description
cancelBubble Boolean reads and writes by default to false, but setting it to true cancels event bubbling;
The returnValue Boolean read-write default is true, but setting it to false cancels the default behavior of events.
srcElement Element target of read-only events;
type String read only the type of event that is triggered;


//  Compatible with target and srcElement function 
  function getTarget(evt){
    var e = evt || window.event;
    return e.target || e.srcElement;      //  Compatible with getting event targets DOM object ;
  }
  document.onclick = function(evt){
    var target = getTarget(evt);
    alert(target);
  }

5 event flow

The event stream describes the order in which events are received from the page. When several elements with events are stacked in 1, click on one of them.
Not only the currently clicked element will trigger the event, but all the elements in the click range will trigger the event.
The flow of events consists of two modes: bubbling and trapping;

1. The event bubbled
One by one from the inside out;

2. Event capture
One by one from the outside in;


//  Modern browsers are all bubble types ; The capture mode is early Netscape The default ;
//  The current browser will be used DOM2 The event binding mechanism of the level model allows you to manually define the event flow pattern ;
  document.onclick = function(){
    alert(' I am a document');
  }
  document.documentElement.onclick = function(){
    alert(' I am a html');
  }
  document.body.onclick = function(){
    alert(' I am a body');
  }
  document.getElementById('box').onclick = function(){
    alert(' I am a div');
  }
  document.getElementsByTagName('input')[0].onclick=function(){
    alert(' I am a input');
  }
  // PS: Click on the input It's going to bubble up document;

//  Prevent event bubbling compatible functions 
  function stopPro(evt){
    var e = evt || window.event;
    //  If there is cancelBubble, It is IE The browser , Set its value to true You can stop the event from bubbling ;
    //  Otherwise do W3C Prevent the event from bubbling in stopPropagation();
    window.event ? e.cancelBubble = true : e.stopPropagation();
  }

Related articles: