javascript: Event Object

Original sentence: Https://Wangdoc.Com/javascript/index.Html

Event objects

Outline

After the incident, it will generate an event object as a parameter passed to the listener function. A native browser Eventobjects, all events are instances of this object, or inherited Event.prototypeobjects.

EventIs a constructor object itself, can be used to create a new instance.

event = new Event(type, options);

EventConstructor takes two parameters. The first parameter typeis a string representing the name of the event; the second argument optionsis an object that represents a configuration of the event object. The targets are of the following two properties.

  • bubbles: Boolean, optional, by default false, indicating whether the event object bubbles.
  • cancelable: Boolean, optional, by default false, indicating whether the event can be canceled, that can use Event.preventDefault()to cancel the event. Once the event is canceled, as if never happened, it does not trigger the default behavior of the browser to the event.
var ev = new Event(
  'look',
  {
    'bubbles': true,
    'cancelable': false
  }
);
document.dispatchEvent(ev);

The code above creates a new lookevent instance, then use the dispatchEventmethod that triggered the event.

Note that, if not explicitly specified bubblesattributes true, generate events can only be in the "capture phase" trigger monitor function.

// HTML 代码为
// <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); // 没有任何输出
}

div.addEventListener('click', callback, false);

var click = new Event('click');
p.dispatchEvent(click);

The above code, pthe elements emit a clickevent that default is not bubbling. div.addEventListenerThe method specified in the bubbling stage monitor, monitor function and therefore does not trigger. If written div.addEventListener('click', callback, true), then the "capture phase" can listen to this event.

On the other hand, if this event is divtriggered on the elements.

div.dispatchEvent(click);

So, regardless of divelements in the bubbling phase is listening, or in the capture phase listeners will trigger the listener function. Because then the divelement is the target event, the question whether the bubble does not exist, divthe elements will always be an event is received, thus leading to the listener function to take effect.

Instance Properties

Event.bubbles,Event.eventPhase

Event.bubblesProperty returns a Boolean value that indicates whether the current event bubbling. This attribute is read-only property, is generally used to know whether the instance of Event bubbling. As mentioned above, unless explicitly declared Eventconstructor generated events, the default is not bubbling.

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

var phase = event.eventPhase;

Event.eventPhaseThere are four possible return values.

  • 0, current events did not happen.
  • 1, the event is currently in the acquisition phase, that is, in ancestor from the node to the destination node of the communication process.
  • 2, the event reaches the target node, ie Event.targetthe node attribute points.
  • 3, in the event bubbling phase, which is in the back-propagation from the target node to node ancestor in the process.

Event.cancelable,Event.cancelBubble,event.defaultPrevented

Event.cancelableProperty returns a Boolean value indicating whether the event can be canceled. This attribute is read-only property, it is generally used to understand the characteristics of Event instances.

Native event most browsers can be canceled. For example, to cancel clickthe event, click on the link will not work. But unless explicitly declared Eventconstructor generated events, the default is not canceled.

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

When the Event.cancelableproperty is true, the call Event.preventDefault()can cancel this event prevents the default behavior of the browser to the event.

If the event is not canceled, calls Event.preventDefault()will not have any effect. So before using this method, the best Event.cancelableproperty 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.cancelBubbleIs a Boolean value that, if true, equivalent to execution Event.stopPropagation(), you can stop the spread of the event.

Event.defaultPreventedProperty returns a Boolean value that indicates whether the event had invoked Event.preventDefaultmethod. This property is read-only.

if (event.defaultPrevented) {
  console.log('该事件已经取消了');
}

Event.currentTarget,Event.target

After the incident, the two will go through the capture and bubbling phases, followed by multiple DOM nodes. Therefore, any point in time there are two nodes associated with the event, a node is the original trigger event ( Event.target), another node event is currently being adopted ( Event.currentTarget). The former is usually the latter's descendant nodes.

Event.currentTargetProperty returns the node event is currently located, that the event is currently being adopted by the node, the node that is currently executing the listener function is located. With the spread of the event, it will become the value of this property.

Event.targetProperty returns the node that triggered the original event, that event occurred first node. This property does not change with the spread of the event.

Event propagation process, the different nodes inside the listener function Event.targetwith the Event.currentTargetvalue of the property is not the same.

// HTML 代码为
// <p id="para">Hello <em>World</em></p>
function hide(e) {
  // 不管点击 Hello 或 World,总是返回 true
  console.log(this === e.currentTarget);

  // 点击 Hello,返回 true
  // 点击 World,返回 false
  console.log(this === e.target);
}

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

The above code, <em>is <p>the child node, click <em>or tap <p>, will lead the listener function is executed. At this time, e.targetalways points to the location of the original click the node, and e.currentTargetpoint to the event propagation process is passing that node. Since the monitor function will only be triggered when the incident, so e.currentTargetalways equate to monitor internal functions this.

Event.type

Event.typeProperty returns a string that represents the type of event. Type of event is specified at the time the event was generated. This property is read-only.

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

Event.timeStamp

Event.timeStampProperty returns a millisecond timestamp indicating the time the event occurred. It is relative to the page loads successfully counted.

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

It is possible return value is an integer, there may be a decimal (high-precision time), depending on the settings of the browser.

Here is an example of a moving velocity calculation mouse, display 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.isTrustedProperty returns a Boolean value that indicates whether the event generated by the real user behavior. For example, the user clicks on the link will have a clickevent that is generated by the user; Eventconstructor generated events, is generated by the script.

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

The above code, evtthe object is generated by the script, the isTrustedproperty returns false.

Event.detail

Event.detailOnly properties browser UI (user interface) that has the event. This property returns a value that represents some information about the event. The specific meaning associated with the event type. For example, for clickand dblclickevents, Event.detailis the number of mouse pressed ( 1indicating that clicking, 2double-clicked, 3represent three strikes); for mouse wheel events, Event.detaila wheel rolling forward from a negative value is negative rolling distance, the value of total return is a multiple of 3.

// HTML 代码如下
// <p>Hello</p>
function giveDetails(e) {
  console.log(e.detail);
}

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

Examples of methods

Event.preventDefault()

Event.preventDefaultMethod to cancel the default behavior of the browser to the current event. For example, click on the link, the browser will jump to another page by default, after using this method, they will not jump up; another example, press the space bar, scroll down the page for some distance, after using this method will not rolled. Premise of this method is to take effect, the event object cancelableproperty true, if it is false, calling this method has no effect.

Note that this method only cancel the default event on the impact of the current element, will not prevent the spread of the event. If you want to stop the spread, you can use stopPropagation()or stopImmediatePropagation()method.

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

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

The above code, the default behavior of the browser is to click the radio button is selected by the abolition of this behavior, you can not select the checkbox lead.

Using this method, it is possible to set a check condition to the text input box. If the user's input does not meet the conditions, you can not input the characters text box.

// HTML 代码为
// <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();
  }
}

The above code text box keypressafter setting event listener function will only input lowercase letters, otherwise enter the default behavior (written text box) event will be canceled, leading to not enter into the text box.

Event.stopPropagation()

stopPropagationThe method prevents the event continues to circulate in the DOM, prevent re-trigger the listener function is defined on the other node, but does not include other event listeners on the current node function.

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

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

The above code, the clickevent will not be further bubbling to elthe parent node.

Event.stopImmediatePropagation()

Event.stopImmediatePropagationWith a way to prevent other event listener function is called, in the current node or other nodes regardless of listener function definition. In other words, the way to stop the spread of the incident, than Event.stopPropagation()more thoroughly.

If the same node for the same event specified multiple monitor functions that will in turn call the order added. As long as there is a listener function calls the Event.stopImmediatePropagationmethod, the other monitor function will not be executed.

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

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

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

In the above code elon the node for clickthe event listener adds two functions l1and l2. Since the l1call event.stopImmediatePropagationmethod, it l2will not be called.

Event.composedPath()

Event.composedPath()Returns an array members are the lowest level nodes in turn bubbling through events and all the upper node.

// HTML 代码如下
// <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]

The above code, clickthe bottom node is the event p, followed up div, body, html, document, Window.

Guess you like

Origin www.cnblogs.com/wbyixx/p/12499292.html