Event object of javascript learning

Event object

overview

After the event occurs, an event object will be generated and passed to the listening function as a parameter. The browser provides an object natively Event, and all events are instances of this object, or inherit Event.prototypethe object.

EventThe object itself is a constructor that can be used to generate new instances.

event = new Event(type, options);

EventThe constructor accepts two parameters. The first parameter typeis a string representing the name of the event; the second parameter optionsis an object representing the configuration of the event object. This object mainly has the following two properties.

  • bubbles: Boolean value, optional, default is false, indicates whether the event object is bubbling.

  • cancelable: Boolean value, optional, default is false, indicating whether the event can be canceled, that is, whether Event.preventDefault()the event can be canceled by using the function. Once an event is canceled, it is as if it never happened, and the browser's default behavior for that event is not triggered.

var ev = new Event(
  'look',
  {
    'bubbles': true,
    'cancelable': false
  }
);
document.dispatchEvent(ev);

The above code creates a new lookevent instance, and then uses dispatchEventthe method to trigger the event.

bubblesNote that if the attribute is not explicitly specified true, the generated event can only trigger the listener function in the "capture phase".

// HTML code is
// <div><p>Hello</p></div>
var div = document.querySelector('div');
var p = document.querySelector('p');
function callback(event) {
  var tag = event.currentTarget.tagName;
  console.log('Tag: ' + tag); // no output
}
div.addEventListener('click', callback, false);
var click = new Event('click');
p.dispatchEvent(click);

In the above code, pthe element emits an clickevent, which does not bubble by default. div.addEventListenerThe method specifies listening during the bubbling phase, so the listening function will not trigger. If written div.addEventListener('click', callback, true), this event can be listened to during the "capture phase".

On the other hand, if this event divfires on the element.

div.dispatchEvent(click);

Then, no matter whether divthe element is listening in the bubbling phase or in the capturing phase, the listening function will be triggered. Because divthe element is the target of the event at this time, there is no question of whether it is bubbling, and divthe element will always receive the event, thus causing the listening function to take effect.

instance attribute

Event.bubbles,Event.eventPhase

Event.bubblesProperty returns a boolean indicating whether the current event will bubble. This attribute is read-only, and is generally used to know whether the Event instance can bubble. As mentioned earlier, unless explicitly stated, Eventthe events generated by the constructor are not bubbling by default.

Event.eventPhaseProperty returns an integer constant representing the current phase of the event. This property is read-only.

var phase = event.eventPhase;

Event.eventPhaseThere are four possible return values ​​for .

  • 0, the event is not currently occurring.

  • 1. The event is currently in the capture phase, that is, it is in the process of propagating from the ancestor node to the target node.

  • 2. The event reaches the target node, that is, Event.targetthe node pointed to by the attribute.

  • 3. The event is in the bubbling stage, that is, it is in the process of back propagation from the target node to the ancestor node.

Event.cancelable,Event.cancelBubble,event.defaultPrevented

Event.cancelableProperty returns a boolean indicating whether the event can be canceled. This property is read-only and is generally used to understand the characteristics of the Event instance.

Most browser's native events are cancelable. For example, to cancel clickthe event, clicking on the link will have no effect. But unless explicitly stated, Eventthe events generated by the constructor cannot be canceled by default.

var evt = new Event('foo');
evt.cancelable  // false

When Event.cancelablethe property trueis , calling Event.preventDefault()can cancel this event, preventing the browser's default behavior for this event.

If the event cannot be canceled, the call Event.preventDefault()has no effect. So before using this method, it is best to use Event.cancelableattributes to determine whether it can be canceled.

function preventEvent(event) {
  if (event.cancelable) {
    event.preventDefault();
  } else {
    console.warn('This event couldn\'t be canceled.');
    console.dir(event);
  }
}

Event.cancelBubbleThe attribute is a boolean value, if set true, it is equivalent to execution Event.stopPropagation(), which can prevent the propagation of the event.

Event.defaultPreventedThe property returns a boolean indicating whether the Event.preventDefaultmethod was called by the event. This property is read-only.

if (event.defaultPrevented) {
  console.log('The event has been canceled');
}

Event.currentTarget,Event.target

After an event occurs, it will go through two stages of capture and bubbling, and pass through multiple DOM nodes in turn. Therefore, any event has two nodes associated with the event, one is the original trigger node of the event ( Event.target), and the other is the node through which the event is currently passing ( Event.currentTarget). The former are usually descendant nodes of the latter.

Event.currentTargetThe property returns the node where the event is currently located, that is, the node through which the event is currently passing, that is, the node where the listener function currently being executed is located. As the event propagates, the value of this property changes.

Event.targetThe property returns the node that originally fired the event, that is, the node where the event originally occurred. This property does not change as the event propagates.

During the event propagation process, the values ​​of the listener functions Event.targetand Event.currentTargetattributes of different nodes are different.

// HTML code is
// <p id="para">Hello <em>World</em></p>
function hide(e) {
  // Regardless of clicking Hello or World, always return true
  console.log(this === e.currentTarget);

  // Click Hello, return true
  // Click World, return false
  console.log(this === e.target);
}

document.getElementById('para').addEventListener('click', hide, false);

In the above code, <em>if <p>the child node is clicked <em>or clicked <p>, it will cause the execution of the monitoring function. At this time, e.targetalways point to the node at the original click position, and e.currentTargetpoint to the node that is passing through during the event propagation process. Since the listener function will only be triggered when the event passes, it e.currentTargetis always equivalent to the inside of the listener function this.

Event.type

Event.typeProperty returns a string representing the event type. The type of event is specified when the event is generated. This property is read-only.

var evt = new Event('foo');
evt.type // "foo"

Event.timeStamp

Event.timeStampProperty returns a millisecond timestamp representing when the event occurred. It is calculated relative to the successful loading of the page.

var evt = new Event('foo');
evt.timeStamp // 3683.6999999995896

Its return value may be an integer or a decimal (high precision timestamp), depending on the browser settings.

Below is an example that calculates the speed of mouse movement, showing the number of pixels moved per second.

var previousX;
var previousY;
var previousT;

window.addEventListener('mousemove', function(event) {
  if (
    previousX !== undefined &&
    previousY !== undefined &&
    previousT !== undefined
  ) {
    var deltaX = event.screenX - previousX;
    var deltaY = event.screenY - previousY;
    var deltaD = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));

    var deltaT = event.timeStamp - previousT;
    console.log(deltaD / deltaT * 1000);
  }

  previousX = event.screenX;
  previousY = event.screenY;
  previousT = event.timeStamp;
});

Event.isTrusted

Event.isTrustedThe property returns a Boolean value indicating whether the event was generated by actual user action. For example, when the user clicks on a link click, an event is generated by the user; Eventthe event generated by the constructor is generated by the script.

var evt = new Event('foo');
evt.isTrusted // false

In the above code, evtthe object is generated by the script, so isTrustedthe property is returned false.

Event.detail

Event.detailProperties are only available for browser UI (User Interface) events. This property returns a value that represents some kind of information about the event. The specific meaning is related to the event type. For example, for clickthe and dblclickevent, Event.detailit is the number of times the mouse is pressed ( 1indicates single click, 2double click, 3triple click); for the mouse wheel event, Event.detailit is the distance of the scroll wheel in the positive direction, and the negative value is the distance of the negative scroll. is a multiple of 3.

// The HTML code is as follows
// <p>Hello</p>
function giveDetails(e) {
  console.log(e.detail);
}

document.querySelector('p').onclick = giveDetails;

instance method

Event.preventDefault()

Event.preventDefaultMethod cancels the browser's default behavior for the current event. For example, after clicking a link, the browser will jump to another page by default. After using this method, it will not jump; scrolled. The prerequisite for this method to take effect is that cancelablethe property of the event object is true, and if so false, calling this method has no effect.

Note that this method only cancels the default effect of the event on the current element, and does not prevent the propagation of the event. If you want to prevent propagation, you can use the stopPropagation()or stopImmediatePropagation()method.

// HTML code is
// <input type="checkbox" id="my-checkbox" />
var cb = document.getElementById('my-checkbox');

cb.addEventListener(
  'click',
  function (e){ e.preventDefault(); },
  false
);

In the above code, the default behavior of the browser is to click the radio button to select it. Canceling this behavior will result in the radio button not being selected.

Using this method, you can set validation conditions for the text input box. If the user's input does not meet the criteria, characters cannot be entered into the text box.

// HTML code is
// <input type="text" id="my-input" />
var input = document.getElementById('my-input');
input.addEventListener('keypress', checkName, false);

function checkName(e) {
  if (e.charCode < 97 || e.charCode > 122) {
    e.preventDefault();
  }
}

After the above code keypresssets the listener function for the event of the text box, only lowercase letters can be input, otherwise the default behavior of the input event (writing into the text box) will be cancelled, resulting in the inability to input content into the text box.

Event.stopPropagation()

stopPropagationThe method prevents the event from continuing to propagate in the DOM, and prevents triggering of listener functions defined on other nodes, but does not include other event listener functions on the current node.

function stopEvent(e) {
  e.stopPropagation();
}

el.addEventListener('click', stopEvent, false);

In the above code, clickthe event will not bubble up further to elthe node's parent node.

Event.stopImmediatePropagation()

Event.stopImmediatePropagationmethod prevents other listener functions of the same event from being called, no matter the listener function is defined on the current node or other nodes. That is, the method prevents the propagation of events Event.stopPropagation()more thoroughly than .

If the same node specifies multiple listener functions for the same event, these functions will be called sequentially according to the order in which they are added. As long as one of the listener functions calls Event.stopImmediatePropagationthe method, the other listener functions will not be executed again.

function l1(e){
  e.stopImmediatePropagation();
}

function l2(e){
  console.log('hello world');
}

el.addEventListener('click', l1, false);
el.addEventListener('click', l2, false);

The above code is elon the node, and two listener functions and clickare added to the event . Since the method was called , it will not be called.l1l2l1event.stopImmediatePropagationl2

Event.composedPath()

Event.composedPath()Returns an array whose members are the bottom-level node of the event and all the upper-level nodes that bubble through in turn.

// The HTML code is as follows
// <div>
//   <p>Hello</p>
// </div>
var div = document.querySelector('div');
var p = document.querySelector('p');

div.addEventListener('click', function (e) {
  console.log(e.composedPath());
}, false);
// [p, div, body, html, document, Window]

In the above code, clickthe bottom-level node of the event is p, and the upward sequence is div, body, html, document, Window.

Guess you like

Origin blog.csdn.net/zy_dreamer/article/details/132115510