preface
This series is before the accumulation of learning, mainly for the JS tutorial entry for learning records. The reference materials used have rookie tutorial, RUan Yifeng JS introductory tutorial series, network road and other websites. The content is based on ECMAScript 5.1, which is the foundation for learning JavaScript syntax. In a state of constant editing and updating.
Mouse events
1. Types of mouse events
Mouse events are mouse-related events that inherit the MouseEvent interface. The specific events are mainly as follows.
- Click: triggered when the mouse is pressed (usually the main button).
- Dblclick: Triggered when you double click on the same element.
- Mousedown: Triggered when the mouse button is pressed.
- Mouseup: Triggered when the mouse key is released.
- Mousemove: Triggered when the mouse moves within a node. This event is triggered continuously when the mouse continues to move. To avoid performance problems, it is recommended to restrict the listener function of this event to run only once in a period of time.
- Mouseenter: This event is triggered when the mouse enters a node, but not when it enters a child node (more on this later).
- Mouseover: Triggered when the mouse enters a node, and again when entering a child node (see more later).
- Mouseout: Triggered when the mouse moves away from a node, as well as from the parent node (see more later).
- Mouseleave: Triggered when the mouse moves away from a node. Leaving the parent node does not trigger this event (more on this later).
- Contextmenu: triggered when the right mouse button is pressed (before the contextmenu appears), or when the contextmenu key is pressed.
- Wheel: Triggered when the mouse wheel is rolled. This event inherits the WheelEvent interface.
The click event means that the user completes a mousedown action and then a Mouseup action in the same location. So, the firing sequence is mousedown first, mouseup next, and Click last.
The dBLClick event is emitted after mouseDown, mouseup, and Click.
The mouseover event and mouseEnter event are both triggered when the mouse enters a node. The difference is that the MouseEnter event fires only once, whereas the Mouseover event fires multiple times on the child nodes whenever the mouse moves within the node.
<ul> <li>item 1</li> <li>item 2</li> </li> </li> item 3</li> </ul> */ var ul = document.querySelector('ul'); // After entering the ul node, the mouseEnter event is emitted only once. // Event. target is the ul node ul.addeventListener ('mouseenter', function (event) { event.target.style.color = 'purple'; setTimeout(function () { event.target.style.color = ''; }, 500); }, false); // After entering the UL node, as long as the child node is moved, // Event. target is the li node ul.addeventListener ('mouseover', function (event) { event.target.style.color = 'orange'; setTimeout(function () { event.target.style.color = ''; }, 500); }, false); // Enter ul node first, then move within the node, mouseleave is not triggered // Only when leaving ul node, Trigger a mouseleave // event.target is ul ul. AddEventListener ('mouseleave', function (event) { event.target.style.color = 'purple'; setTimeout(function () { event.target.style.color = ''; }, 500); }, false); // Enter ul node first, then move inside the node, // Event. target is the li node ul.addeventListener ('mouseout', function (event) { event.target.style.color = 'orange'; setTimeout(function () { event.target.style.color = ''; }, 500); }, false);Copy the code
Entering the child node inside the parent does not trigger the mouseEnter event, but does trigger the Mouseover event.
Both mouseout and mouseleave events are triggered when the mouse moves away from a node. The difference between the two is that the mouseleave event does not fire when leaving a child inside the parent element, whereas the Mouseout event does.
2. Overview of MouseEvent interface
The MouseEvent interface represents mouse-related events, such as clicking (click), double-clicking (dblclick), releasing (mouseup), and pressing (mouseDown). The event objects are instances of MouseEvents. In addition, scroll events and drag events are MouseEvent instances.
The MouseEvent interface inherits the Event interface, so it has all the attributes and methods of the Event. It also has its own properties and methods.
The browser natively provides a MouseEvent constructor to create a new MouseEvent instance
var event = new MouseEvent(type, options);
Copy the code
The first argument is a string that represents the event name; The second parameter is an event configuration object, which is optional. In addition to the instance configuration properties of the Event interface, the object can be configured with the following properties, all of which are optional.
ScreenX: Value, the horizontal position of the mouse relative to the screen in pixels. The default value is 0. Setting this property does not move the mouse. ScreenY: Value, the vertical position of the mouse relative to the screen (in pixels), otherwise the same as screenX. ClientX: Value, the horizontal position of the mouse relative to the program window in pixels. The default value is 0. Setting this property does not move the mouse. ClientY: Value, vertical position of the mouse relative to the program window (in pixels), otherwise same as clientX. CtrlKey: Boolean value, whether Ctrl key is pressed at the same time. Default value: false. ShiftKey: Boolean value that indicates whether the Shift key is also pressed. The default value is false. AltKey: Boolean value for whether to press Alt key at the same time. Default value is false. MetaKey: Boolean value, whether to press the Meta key at the same time. The default value is false. Button: A value indicating which mouse button was pressed. The default value is 0, indicating that the primary key was pressed (usually the left mouse button) or that the current event did not define this property. 1 means to press the auxiliary key (usually the middle button of the mouse) and 2 means to press the next key (usually the right button of the mouse). Buttons: A value that indicates which mouse keys are pressed. This is a three-bit binary value that defaults to 0 (no keys are pressed). 1 (binary 001) means to press the primary key (usually the left key), 2 (binary 010) means to press the next key (usually the right button), and 4 (binary 100) means to press the secondary key (usually the middle key). Therefore, a return of 3 (binary 011) indicates that both left and right keys were pressed. RelatedTarget: Node object representing the associated node of the event, null by default. The mouseEnter and mouseover events represent the element node that the mouse has just left. The mouseout and mouseleave events represent the element node that the mouse is entering.Copy the code
3. Instance properties of the MouseEvent interface
AltKey, MouseEvent. CtrlKey, MouseEvent. MetaKey, MouseEvent
AltKey, MouseEvent. CtrlKey, MouseEvent. MetaKey, MouseEvent. ShiftKey all return a Boolean value indicating whether to press the corresponding key when the event occurs. They are all read-only properties.
- AltKey property: Alt key
- CtrlKey Property: Ctrl key
- MetaKey property: Meta key (Mac keyboard is a four-petal flower, Windows keyboard is a Windows key)
- ShiftKey property: Shift key
3.2 MouseEvent. Button, MouseEvent. Buttons
The mouseEvent. button property returns a number indicating which mouse key was pressed when the event occurred. This property is read-only.
- 0: The primary key is pressed (usually left), or the event does not initialize the property (such as the Mousemove event).
- 1: Press the secondary key (usually the middle key or the wheel key).
- 2: Press the next key (usually the right button).
The mouseEvent. buttons property returns a three-bit value indicating which keys were pressed at the same time. It deals with pressing multiple mouse keys at the same time. This property is read-only.
- 1: the binary value is 001 (1 in decimal), indicating that the left key is pressed.
- 2: the binary value is 010 (2 in decimal), indicating that the right button is pressed.
- 4: The binary value is 100 (4 in decimal), indicating that the middle key or wheel key is pressed.
When multiple keys are pressed at the same time, each key has a value for its bit. For example, pressing the left and right keys at the same time returns 3 (011 in binary).
3.3 MouseEvent clientX, MouseEvent. ClientY
The MouseEvent. ClientX property returns the horizontal coordinate (in pixels) of the mouse position relative to the top left corner of the browser window, and the MouseEvent. ClientY property returns the vertical coordinate. Both properties are read-only.
The two properties also have aliases mouseEvent. x and MouseEvent.y, respectively.
3.4 MouseEvent movementX, MouseEvent. MovementY
The mouseEvent.MovementX property returns the horizontal distance in pixels between the current location and the last Mousemove event. Numerically, it is equal to the following formula.
currentEvent.movementX = currentEvent.screenX - previousEvent.screenX
Copy the code
The mouseEvent. movementY property returns the vertical distance in pixels between the current position and the last Mousemove event. Numerically, it is equal to the following formula.
Currentevent.movementy = currentevent.screeny - previousevent.screeny.Copy the code
Both properties are read-only.
3.5 MouseEvent screenX, MouseEvent. ScreenY
The mouseEvent.screenx property returns the horizontal coordinate (in pixels) of the mouse position relative to the upper-left corner of the screen.
The mouseEvent. screenY property returns the vertical coordinates. Both properties are read-only.
3.6 MouseEvent offsetX, MouseEvent. OffsetY
The mouseEvent. offsetX property returns the horizontal distance (in pixels) between the mouse position and the padding edge to the left of the target node, and the mouseEvent. offsetY property returns the vertical distance from the padding edge above the target node. Both properties are read-only.
< span style> p {width: 100px; height: 100px; padding: 100px; } </style> <p>Hello</p> */ var p = document.querySelector('p'); p.addEventListener( 'click', function (e) { console.log(e.offsetX); console.log(e.offsetY); }, false );Copy the code
If you click over the center of the P element, it returns 150, 150. So the center position from the left and top padding edge is equal to the width of the padding (100 pixels) plus half the width of the element’s content area (50 pixels).
3.7 MouseEvent pageX, MouseEvent. PageY
The mouseEvent. pageX property returns the distance in pixels from the left edge of the document, and the mouseEvent. pageY property returns the distance in pixels from the upper edge of the document. Their return values all include invisible parts of the document. Both properties are read-only.
3.8 MouseEvent. RelatedTarget
The mouseEvent.relatedTarget property returns the node associated with the event. This property returns NULL for events that have no associated node. This property is read-only.
<div id="outer" style="height:50px; width:50px; border-width:1px solid black;" > <div id="inner" style="height:25px; width:25px; border:1px solid black;" ></div> </div> */ var inner = document.getElementById('inner'); inner.addEventListener('mouseover', Function (event) {console.log(' enter '+ event.target.id +' leave '+ event.relatedTarget.id); }, false); inner.addEventListener('mouseenter', Function (event) {console.log(' enter '+ event.target.id +' leave '+ event.relatedTarget.id); }); Inner. AddEventListener ('mouseout', function () {console.log(' leave '+ event.target.id +' enter '+ event.relatedTarget.id); }); Inner. AddEventListener ("mouseleave", function (){console.log(' leave '+ event.target.id +' enter '+ event.relatedTarget.id); }); // mouse from outer into inner, output // into inner from outer // into inner from outer // mouse from inner into outer, Exit // exit inner into outer // exit inner into outerCopy the code
4. Instance methods of the MouseEvent interface
MouseEvent.getModifierState()
MouseEvent. GetModifierState method returns a Boolean value, said any press specific function keys. Its argument is a string representing the function key.
document.addEventListener('click', function (e) {
console.log(e.getModifierState('CapsLock'));
}, false);
Copy the code
Find out if the user pressed the uppercase key.
5. WheelEvent interface
The WheelEvent interface inherits the MouseEvent instance, which represents the instance object of the mouse WheelEvent. Currently, there is only one “wheel” event related to the mouse wheel, and an instance of this event is generated when the user scrolls the mouse wheel.
Browsers natively provide the WheelEvent() constructor, which is used to generate WheelEvent instances.
var wheelEvent = new WheelEvent(type, options);
Copy the code
The first is a string that represents the event type. For wheel events, this value can only be wheel. The second parameter is the configuration object for the event. In addition to the configuration properties of Event and UIEvent, the object can also accept the following properties, all of which are optional.
- DeltaX: value representing the amount of horizontal scrolling of the wheel. The default value is 0.0.
- DeltaY: Number representing the vertical scrolling of the wheel. The default value is 0.0.
- DeltaZ: Indicates the amount of z-axis scrolling of the scroll wheel. The default value is 0.0.
- DeltaMode: A numeric value representing the unit of the relevant rolling event, which applies to the above three attributes. 0 means scrolling in pixels, 1 in rows, 2 in pages, and the default is 0.
Instance attributes
WheelEvent Event instances have some instance properties of their own, but no instance methods, in addition to instance properties and instance methods of Event and MouseEvent.
The following properties are read-only.
- Wheelevent. deltaX: Number representing the horizontal roll of a wheel.
- Wheelevent. deltaY: Value representing the amount of vertical scroll of a wheel.
- Wheelevent. deltaZ: Value representing the z-axis roll of a wheel.
- Wheelevent. deltaMode: Numeric value representing units of the above three properties, 0 for pixels, 1 for rows, and 2 for pages.
Keyboard events
1. Types of keyboard events
Keyboard events are triggered by the user hitting the keyboard, including keyDown, KeyPress, and KeyUp, which inherit the KeyboardEvent interface.
- Keydown: Triggered when the keyboard is pressed.
- Keypress: This event is triggered when a valued key is pressed, that is, Ctrl, Alt, Shift, Meta, etc. For a valued key, the keyDown event is triggered and then the keydown event is triggered.
- Keyup: This event is triggered when the keyboard is released.
If the user keeps pressing the key without releasing it, the keyboard events will fire consecutively, in the following order.
keydown keypress keydown keypress ... (Repeat the process) KeyupCopy the code
2. KeyboardEvent interface overview
The KeyboardEvent interface is used to describe the user’s interaction with the keyboard. This interface inherits the Event interface and defines its own instance properties and instance methods.
Browsers natively provide the KeyboardEvent constructor to create new instances of keyboard events.
new KeyboardEvent(type, options)
Copy the code
The first argument is a string representing the event type; The second parameter is an event configuration object, which is optional. In addition to the properties provided by the Event interface, you can configure the following fields, which are optional.
- Key: string. The key is currently pressed. The default value is an empty string.
- Code: string, representing the current key pressed as a string. Default is empty string.
- Location: integer, the location of the current key press. Default is 0.
- CtrlKey: Boolean value, whether to press Ctrl key. Default value: false.
- ShiftKey: Boolean value, whether to press Shift key. Default: false.
- AltKey: Boolean value for whether to press Alt key. Default is false.
- MetaKey: Boolean value, whether to press the Meta key. The default value is false.
- Repeat: Boolean value, whether to repeat the key. Default: false
3. Instance properties of KeyboardEvent
AltKey, KeyboardEvent. CtrlKey, KeyboardEvent. MetaKey, KeyboardEvent. ShiftKey
Are read-only properties that return a Boolean value indicating whether the corresponding key was pressed.
Keyboardevent. altKey: Whether to press Alt key keyboardevent. ctrlKey: Whether to press Ctrl key keyboardevent. metaKey: Whether to press the Meta key (Mac is a four-pronged flower, Windows is a Windows key) Function showChar(e) {console.log('ALT: '+ e.alt key); console.log('CTRL: ' + e.ctrlKey); console.log('Meta: ' + e.metaKey); console.log('Shift: ' + e.shiftKey); } document.body.addEventListener('keydown', showChar, false);Copy the code
3.2 KeyboardEvent. Code
The keyboardevent. code property returns a string representing the string form of the currently pressed key. This property is read-only.
Common keys in string form:
Digital keys 0-9: Returns Digital0-Digital9 Letter keys A-Z: returns KEYA-KEYZ function keys F1-F12: Returns F1-F12 Direction keys: Alt key: Returns AltLeft or AltRight Shift key: Returns ShiftLeft or ShiftRight Ctrl key: Returns ControlLeft or ControlRightCopy the code
3.3 KeyboardEvent. Key
The keyboardevent. key property returns a string representing the name of the key that was pressed. This property is read-only.
Returns a printable character, such as a number or letter, if the key pressed represents that character.
If the key pressed represents a special character that cannot be printed, return predefined key values such as Backspace, Tab, Enter, Shift, Control, Alt, CapsLock, Esc, Spacebar, PageUp, PageDown, End, Home, Left, Right, Up, Down, PrintScreen, Insert, Del, Win, F1 ~ F12, NumLock, Scroll, etc.
Returns the key name of the symbol key if both a control key and a symbol key are pressed. For example, pressing Ctrl + A returns a; Shift + A returns a capital A.
If the key name cannot be identified, the string Unidentified is returned.
3.4 KeyboardEvent. The location
The keyboardevent. location property returns an integer indicating the region of the keyboard in which the key is pressed. It may take the following values.
0: in the main area of the keyboard, or unable to determine which area. 1: On the left side of the keyboard, only for keys that have two positions (such as Ctrl and Shift). 2: On the right side of the keyboard, only for keys that have two positions (such as Ctrl and Shift). 3: on the numeric keypad.Copy the code
3.5 KeyboardEvent. Repeat
KeyboardEvent. Repeat returns a Boolean value indicating whether the key is being held to determine whether the key is repeated, meaning that the browser will continue to trigger keyDown and KeyPress events until the user releases his grip.
4. KeyboardEvent instance method
KeyboardEvent.getModifierState()
KeyboardEvent. GetModifierState () method returns a Boolean value that indicates whether or not the press or activating the specified function keys. Its common parameters are as follows.
Alt: Alt: CapsLock: uppercase lock Control: Ctrl Meta: Meta NumLock: NumLock key Shift: Shift key if (event.getModifierState('Control') + event.getModifierState('Alt') + Event.getModifierState ('Meta') > 1) { return; // As long as Control, Alt, Meta, press any two or more keys simultaneously to return. }Copy the code
Progress of the event
The type of progress event
Progress events are used to describe the progress of resource loading. They are triggered by AJAX requests, < IMG >,
- Abort: Triggered when an external resource aborts loading, such as user cancellation. This event is not emitted if an error causes abort.
- Error: Triggered when external resources cannot be loaded due to an error.
- Load: Triggered when external resources are loaded successfully.
- Loadstart: triggered when external resources start to load.
- Loadend: Triggered when an external resource stops loading, following events such as error, abort, and load.
- Progress: continuously triggered during the loading of external resources.
- Timeout: Triggered when loading times out.
image.addEventListener('load', function (event) {
image.classList.add('finished');
});
image.addEventListener('error', function (event) {
image.style.display = 'none';
});
Copy the code
After the image element is loaded, add a Finished Class for the image element. If the load fails, set the image element’s style to undisplayed.
Sometimes the image load will be completed before the script runs, especially if the script is placed at the bottom of the page, so it is possible that the load and error event listeners will not execute at all. So, a more reliable way is to use the complete attribute to check if the load is complete.
function loaded() {
// ...
}
if (image.complete) {
loaded();
} else {
image.addEventListener('load', loaded);
}
Copy the code
Since the element node of the DOM does not provide an attribute to load an error, the listener for error events is best placedElement in order to ensure 100% execution in case of a load error.
<img src="/wrong/url" onerror="this.style.display='none';" />
Copy the code
A listener for a loadend event can be used instead of a listener for abort, load, or error events because it always occurs after these events.
The loadEnd event itself does not provide a reason for the end of the progress, but you can use it to do something that all loading end scenarios need to do.
In addition, error events have the special property of not bubbling. Therefore, the child element’s error event does not trigger the parent element’s error event listener.
ProgressEvent interface
The ProgressEvent interface is used to describe the progress of external resource loading, such as AJAX loading, ,
The browser natively provides the ProgressEvent() constructor, which generates event instances.
new ProgressEvent(type, options)
Copy the code
The first argument is a string that represents the type of event, which is required. The second parameter is an optional configuration object representing the properties of the event. In addition to the configuration properties of the Event interface, configuration objects can use the following properties, all of which are optional.
- LengthComputable: A Boolean value indicating whether the total amount of the load is computable or not. Default is false.
- Loaded: an integer indicating the amount loaded. The default value is 0.
- Total: indicates the total number of loads. The default value is 0.
ProgressEvent has corresponding instance properties.
- ProgressEvent.lengthComputable
- ProgressEvent.loaded
- ProgressEvent.total
If ProgressEvent lengthComputable to false, ProgressEvent. The total is meaningless.
Download process progress event:
var xhr = new XMLHttpRequest(); xhr.addEventListener('progress', updateProgress, false); xhr.addEventListener('load', transferComplete, false); xhr.addEventListener('error', transferFailed, false); xhr.addEventListener('abort', transferCanceled, false); xhr.open(); function updateProgress(e) { if (e.lengthComputable) { var percentComplete = e.loaded / e.total; } else {console.log(' can't calculate progress '); }} function transferComplete(e) {console.log(' transfer finished '); } function transferFailed(evt) {console.log(' error occurred during transfer '); } function transferCanceled(evt) {console.log(' User canceled the transfer '); }Copy the code
Upload progress event, in which all listener functions are placed on top of the XMLHttprequest.upload object.
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', updateProgress, false);
xhr.upload.addEventListener('load', transferComplete, false);
xhr.upload.addEventListener('error', transferFailed, false);
xhr.upload.addEventListener('abort', transferCanceled, false);
xhr.open();
Copy the code