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 Event
objects, all events are instances of this object, or inherited Event.prototype
objects.
Event
Is a constructor object itself, can be used to create a new instance.
event = new Event(type, options);
Event
Constructor takes two parameters. The first parameter type
is a string representing the name of the event; the second argument options
is an object that represents a configuration of the event object. The targets are of the following two properties.
bubbles
: Boolean, optional, by defaultfalse
, indicating whether the event object bubbles.cancelable
: Boolean, optional, by defaultfalse
, indicating whether the event can be canceled, that can useEvent.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 look
event instance, then use the dispatchEvent
method that triggered the event.
Note that, if not explicitly specified bubbles
attributes 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, p
the elements emit a click
event that default is not bubbling. div.addEventListener
The 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 div
triggered on the elements.
div.dispatchEvent(click);
So, regardless of div
elements in the bubbling phase is listening, or in the capture phase listeners will trigger the listener function. Because then the div
element is the target event, the question whether the bubble does not exist, div
the elements will always be an event is received, thus leading to the listener function to take effect.
Instance Properties
Event.bubbles,Event.eventPhase
Event.bubbles
Property 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 Event
constructor generated events, the default is not bubbling.
Event.eventPhase
Property returns an integer constant representing the stage of current events. This property is read-only.
var phase = event.eventPhase;
Event.eventPhase
There 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.target
the 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.cancelable
Property 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 click
the event, click on the link will not work. But unless explicitly declared Event
constructor generated events, the default is not canceled.
var evt = new Event('foo');
evt.cancelable // false
When the Event.cancelable
property 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.cancelable
property 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.cancelBubble
Is a Boolean value that, if true
, equivalent to execution Event.stopPropagation()
, you can stop the spread of the event.
Event.defaultPrevented
Property returns a Boolean value that indicates whether the event had invoked Event.preventDefault
method. 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.currentTarget
Property 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.target
Property 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.target
with the Event.currentTarget
value 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.target
always points to the location of the original click the node, and e.currentTarget
point to the event propagation process is passing that node. Since the monitor function will only be triggered when the incident, so e.currentTarget
always equate to monitor internal functions this
.
Event.type
Event.type
Property 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.timeStamp
Property 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.isTrusted
Property 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 click
event that is generated by the user; Event
constructor generated events, is generated by the script.
var evt = new Event('foo');
evt.isTrusted // false
The above code, evt
the object is generated by the script, the isTrusted
property returns false
.
Event.detail
Event.detail
Only 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 click
and dblclick
events, Event.detail
is the number of mouse pressed ( 1
indicating that clicking, 2
double-clicked, 3
represent three strikes); for mouse wheel events, Event.detail
a 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.preventDefault
Method 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 cancelable
property 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 keypress
after 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()
stopPropagation
The 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 click
event will not be further bubbling to el
the parent node.
Event.stopImmediatePropagation()
Event.stopImmediatePropagation
With 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.stopImmediatePropagation
method, 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 el
on the node for click
the event listener adds two functions l1
and l2
. Since the l1
call event.stopImmediatePropagation
method, it l2
will 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, click
the bottom node is the event p
, followed up div
, body
, html
, document
, Window
.