Quick understanding of JavaScript events

hireny 2021-01-24 11:54:25
quick understanding javascript events


summary

JavaScript And HTML The interaction between them is realized through events . event , It's just a moment of interaction in a document or browser window . You can use listeners ( Or handler ) To schedule events , So that when the event occurs, the corresponding code . This model is called observer pattern in traditional software engineering , Support page behavior (JavaScript Code ) And the look of the page (HTML and CSS Code ) Loose coupling between .

Flow of events

Flow of events Describes the order in which events are received from the page .IE and Netscape The development team proposed two solutions to implement event flow , Event bubble flow and event capture flow .

IE The proposed scheme is event bubbling flow , Trigger from the most specific element , And then propagate up to the document node .

image

Netscape The solution proposed by the team is event capture flow , Event capture starts from the document node and propagates to the most specific elements . Event capture is actually to intercept an event before it reaches its final destination .

image

DOM Flow of events

DOM2 Events According to the specification, the event flow is divided into 3 Stages : Event capture 、 Reaching goals and events bubbling .

  1. Event capture phase : Events look up the corresponding elements from the top down , Until the event is captured .
  2. Reach the target stage : After reaching the target element, execute the corresponding processing function of the event .
  3. Event bubbling stage : Events bubble from the target element .

image

stay DOM In the event stream , Practical goals (<div> Elements ) No events are received during the capture phase . This is because the capture phase starts from document To <html> Until then <body> It's over . Next stage , That will be <div> That triggers an event on the element " Reach the target " Stage , It's usually considered part of the bubbling phase in event processing . then , The bubbling phase begins , Event back propagation to document .

Event handling

An event is an action performed on the browser . Such as clickload etc. . Event handler ( Or event listener ) Is the function called in response to an event .

HTML Event handler

It can be used in the HTML Element to specify what can be executed through attributes JavaScript The value of the code . As shown below :

<input type="button" value="HTML Event Handler" onclick="alert('Click HTML Event')" />

stay HTML The event handler defined in can contain precise action instructions , You can also call scripts defined elsewhere on the page :

<input type="button" value="HTML Event Handler" onclick="handleHTMLEvent()" />
<script>
function handleHTMLEvent() {
alert("Click HTML Event");
}
</script>

Calling handleHTMLEvent() You click the button before the function , There will be mistakes . Can be HTML Event handlers are encapsulated in try/catch In block :

<input type="button" value="HTML Event Handler 2" onclick="try{handleHTMLEvent()} catch (e) {}" />

This kind of event handler makes HTML And JavaScript Strong coupling , Not conducive to maintenance .

DOM0 Event handler

adopt JavaScript Get the event handler and assign a function to the event handler property .

<input id="btn" type="button" value="DOM Event Handler" />
<script>
var btn = document.getElementById('btn');
btn.onclick = function () {
alert("Click DOM Event");
}
</script>

Use DOM0 Methods functions that assign values to event handlers are considered methods of elements . What you get at this time this Equal to the element of the event handler . Adding event handlers in this way registers in the bubbling phase of the event flow .

DOM2 Event handler

DOM2 Events Definition addEventListener() and removeEventListener() Two methods , For assignment and removal of event handlers . all DOM Nodes contain both methods , They receive 3 Parameters : Event name 、 Event handler and a Boolean value , A Boolean value represents the event flow phase that invokes the event handler ,true In the capture phase ,false( Default ) In bubbling stage .

<input id="btn" type="button" value="DOM Event Handler" />
<script>
var btn = document.getElementById('btn');
btn.addEventListener("click", () => {
alert("DOM2 Event Handler");
}, false);
</script>

Use addEventListener() You can add multiple event handlers for the same event .

var btn = document.getElementById('btn');
btn.addEventListener("click", () => {
alert("DOM2 Event Handler");
}, false);
btn.addEventListener("click", () => {
alert("Rep DOM2 Event Handler");
}, false);

Use removeEventListener() And introduce into addEventListener() Same parameters to remove .

var btn = document.getElementById('btn');
btn.addEventListener("click", () => {
alert("DOM2 Event Handler");
}, false);
btn.removeEventListener("click", function () { // No effect
alert("Remove DOM2 Event Handler");
}, false);

But this event handler that passes in anonymous functions cannot be removed .removeEventListener() It has to be with addEventListener() The event handler passed in must be the same .

var btn = document.getElementById('btn');
var handler = function() {
alert("DOM2 Event Handler");
}
btn.addEventListener("click", handler, false);
btn.removeEventListener("click", handler, false); // Effective 

Most of the time , Event handlers are added to the bubbling phase of the event flow , The main reason is good cross browser compatibility . Registering an event handler in the capture phase is usually used to intercept an event before it reaches its specified target . If you don't need to intercept , Do not use event capture .

IE Event handler

IE Realized attachEvent() and detachEvent() Methods are used to assign and remove event handlers . Receive two of the same parameters : The name of the event handler and the event handler functions .IE8 Previously, only event bubbling was supported , Use attachEvent() Will be added to the bubbling phase .

var btn = document.getElementById("btn");
btn.attachEvent("onclick", function() {
alert("IE Event Handler");
});

The event handler at this point is running in the global scope .this be equal to window. You can also add multiple event handlers to an element , But event handlers are triggered in the reverse order of addition .

Event object

DOM When an event occurs, relevant information is collected and stored in event In the object . The object will contain elements of some events 、 Type and other basic information .

In the browser ,event Object is the only parameter passed to the event handler . You can use event objects when you add event handlers :

<input id="btn" type="button" value="DOM Event Object" onclick="alert(event.type)">
<script>
var btn = document.getElementById("btn");
btn.onclick = function(event) {
alert(event.type);
};
btn.addEventListener("click", (event) => {
alert(event.type);
}, false);
</script>

The following table lists all the properties and methods :

attribute / Method type read / Write explain
bubbles Boolean value read-only Indicates whether the event is bubbling
cancelable Boolean value read-only Indicates whether the event can be cancelled
currentTarget Elements read-only The element of the current event handler
defaultPrevented Boolean value read-only true Indicates that... Has been called preventDefault() Method (DOM3 Events Newly added )
detail Integers read-only Only UIEvent( The user interface ) Events have . Returns a number , Some kind of information that represents an event . Such as click event ,detail Returns the number of mouse presses .
eventPhase Integers read-only Indicates to which stage the event flow is being processed :1 Represents the capture phase ,2 On behalf of reaching the target ,3 Represents the bubbling stage
target Elements read-only The objective of the event
isTrusted Boolean value read-only true Indicates that the event was initiated by the browser .false Indicates that the event is created by a script 、 modify 、 adopt EventTarget.dispatchEvent() distributed
type character string read-only The type of event triggered
preventDefault() function read-only Default behavior for canceling Events . Only cancelable by true To call this method
stopImmediatePropagation() function read-only Used to cancel subsequent event capture or event bubbling , And prevent any subsequent event handler from being called (DOM3 Events Newly added )
stopPropagation() function read-only Prevent further propagation of current events in the capture and bubbling phases

Inside the event handler , about currentTarget and target Two attributes , When you add an event handler directly to the target ,this And they are equal .

<body>
<input id="btn" type="button" value="DOM Event Object" />
</body>
<script>
let btn = document.getElementById("btn");
btn.onclick = function(event) {
alert(event.currentTarget === this);
alert(event.target === this);
};
</script>

If you add an event handler to the parent of the button , The result is currentTarget and document.body and this equal , Because it's an element that registers event handlers . and target Property is equal to the button itself , because click Events are the real goal . But the button itself doesn't register an event handler ,click Event bubbling to document.body, The handler that triggers the registration .

document.body.onclick = function (event) {
alert(event.currentTarget === document.body); // true
alert(this === document.body); // true
alert(event.target === this); // false
alert(event.target === document.getElementById("btn")); // true
}

preventDefault() Method is used to block the default action for a specific event . such as , The default behavior of links is to navigate to href Property specified URL. If you want to stop this navigation behavior , Can be in onclick Cancel in the event handler , As the following example shows :

let link = document.getElementById('link');
link.onclick = function (event) {
event.preventDefault();
}

Anything that can pass through preventDefault() Events that cancel the default behavior , Its event object is cancelable Property will be set to true.

stopPropagation() Method is used to immediately block the flow of events in DOM Spread through the structure , Cancel subsequent event capture or bubbling . for example , Is added directly to the event handler of the button stopPropagation(), Can stop document.body Register event handler execution on . such as :

let btn = document.getElementById("btn");
btn.onclick = function(event) {
console.log("Clicked");
event.stopPropagation();
};
document.body.onclick = function(event) {
console.log("Body clicked");
};

IE Event objects also contain properties and methods related to the specific events that cause them to be created , Many of them are related to DOM Properties correspond to methods . Such as srcElement Corresponding DOM Medium target,returnValue Properties corresponding to DOM Medium preventDefault() Methods, etc. .

Event type

DOM3 Events stay DOM2 Events New event types are redefined and added :

  • UI Event: User interface events , Relating to BOM Interactive general browser Events .
  • Focus Event: "Event" , Triggered when an element gains and loses focus .
  • Mouse Event: Mouse events , Triggered when using the mouse to perform certain actions on a page .
  • Wheel Event: Wheel event , Triggered when using a mouse wheel or similar device .
  • Input Event: Input event , Trigger when entering text into a document .
  • Keyboard Event: Keyboard events , Triggered when using the keyboard to perform certain actions on a page .
  • Composition Event: Composite event , Using some kind of IME(Input Method Editor, input method editor ) Trigger when entering characters .

User interface events

User interface events or UI Events are not necessarily related to user actions . This kind of thing happens in DOM Norms existed in some form before they appeared , They are reserved for backward compatibility .UI The main events are as follows .

  • load: stay window Trigger when the page is loaded , stay <frameset> To be taken in by all <frame> Trigger after loading , stay <img> Element is triggered when the image is loaded , stay <object> Element when the corresponding object is loaded .
  • unload: stay window Trigger when the cheated page is completely unloaded , stay <frameset> To be taken in by all <frame> Trigger after unloading , stay <object> Element when the corresponding object is unloaded .
  • abort: stay <object> Element is triggered when the user terminates the download ahead of time before the corresponding object is loaded .
  • error: stay window Fall for it JavaScript Trigger when an error is reported , stay <img> Element when the specified image cannot be loaded , stay <object> Element when the corresponding object cannot be loaded , stay <frameset> Fall for one or more <frame> Triggered when the load cannot be completed .
  • select: In the text box (<input> or <textarea>) Triggered when the user selects one or more characters .
  • resize: stay window or <frame> Triggered when a window or window is zoomed .
  • scroll: Triggered when the user scrolls an element that contains a scroll bar .<body> Element contains the scroll bar of the loaded page .

majority HTML Incident and window Objects are related to form controls .

except DOMActivate, These events DOM2 Events All of them are classified as HTML Events.

"Event"

When an element in a page gets ( The user selects ) Or trigger the focus event when the focus is lost . There are several kinds of focus events :

  • blur: Triggered when an element loses focus . Events don't bubble .
  • focus: Triggered when the element gets focus . Events don't bubble .
  • focusin: Triggered when the element gets focus . yes focus Bubble version of the event .
  • focusout: Triggered when an element loses focus . yes blur The universal version of .

DOMFocusIn and DOMFocusOut yes focus And blur The bubble version of , These two events are Opera Newly added , But it has been abandoned , There may be some browsers supporting .focusin and focusout, These two events are IE Browser new , Has been DOM3 Events Standardization .

When the focus moves from one element in the page to another , The following events will occur in turn :①focusout Trigger on an element that has lost focus ;②focusin Trigger on the element that gets the focus ;③blur Trigger on an element that has lost focus ;④DOMFocusOut Trigger on an element that has lost focus ;⑤focus Trigger on the element that gets the focus ;⑥DOMFocusIn Trigger on the element that gets the focus .

Mouse events

Mouse event is a common event type , Inherit MouseEvent Interface .DOM Events Defined 9 Mouse events in .

  • click: Triggered when the user clicks the primary key of the mouse .
  • dblclick: Triggered when the user double clicks the primary key of the mouse .DOM3 Event Standardize it .
  • mousedown: Triggered when the user presses any mouse button .
  • mousemove: Repeatedly triggered when the user moves the mouse over the element . Events cannot be triggered through the keyboard .
  • mouseout: Triggered when the user moves the mouse away from the element . The moving element can be an external element of the original element , It can also be a child of the original element . Events cannot be triggered through the keyboard .
  • mouseover: Triggered when the user moves the mouse cursor from the outside of the element to the inside of the element . Cannot be triggered by keyboard .
  • mouseup: Triggered when the user releases the mouse . Cannot be triggered by keyboard .
  • mouseenter: Triggered when the user hovers over certain elements . It's not a bubble thing , It doesn't trigger when hovering over a descendant element .DOM3 Events New events .
  • mouseleave: Triggered when the user moves the mouse away from the hovering element . It's not a bubble thing , It doesn't trigger when passing through descendant elements .DOM3 Events New events .
  • mousewheel: Wheel event , Subcategories of mouse events . Reflect the interaction of mouse wheel or similar device .

There is a relationship between events , Canceling the default behavior for mouse events affects other events .

Keyboard events

Keyboard events are triggered when the user operates the keyboard .DOM2 Events Finally, no keyboard event was defined , It's all based on DOM0 Realized .

DOM3 Events Provides a specification for keyboard events , contain 3 Events :

  • keydown: Triggered when the user presses the keyboard .
  • keypress: Triggered when the user presses a key on the keyboard and generates a character .DOM3 Events Abandoned keypress event , recommend textInput event .
  • keyup: Triggered when the user releases a key on the keyboard .

Although all elements support these events , But it's easiest to see when the user enters content in the text box .

The correct sequence of events triggered by the user pressing a character key on the keyboard is as follows :①keydown;②keypress;③keyup.keydown and keypress Events are triggered before the text box changes ,keyup Event is triggered after the text box changes . Non character keys are omitted keypress event .

But when the user presses the key long enough , It will start “ Repeat events automatically ”:keydown and keypress It's repeated , Until the key is released , Will trigger keyup event . Non character keys are omitted keypress Event steps , Constantly triggering keydown event , It doesn't trigger until it's released keyup event .

Input event

DOM3 Events introduce textInput Input event , It's right keypress Extension of events , Used to capture text input more easily before the text is displayed to the user .textInput Triggers before the text is inserted into the text box .

Only editable areas support textInput event , Such as text field , And it's only triggered when a character is inserted . The event is Event Object added event.data attribute , This property contains the newly inserted character .

Composite event

DOM3 Events New composite event , For handling use IME Complex input sequence when input .IME It allows users to enter characters that are not on the physical keyboard . For example, users with Latin alphabet keyboards can use IME Input Japanese .IME You usually need to press multiple keys to enter a character . Synthetic events are used to detect and control this input . Synthetic events are as follows 3 in :

  • compositionstart: stay IME Triggered when the text synthesis system is turned on , Indicates that input is about to begin .
  • compositionupdate: Trigger when a new character is inserted into the input field .
  • compositionend: stay IME Triggered when the text synthesis system is turned off , Indicates that normal keyboard input is restored .

Synthetic events are similar to input events in many ways . When a composite event is triggered , The event target is the input field that receives the text . The only added event attribute is data, The values included vary depending on the situation :

  • stay compositionstart Incident , Contains the text being edited ( for example , Text has been selected but not replaced );
  • stay compositionupdate Incident , Contains the new character to insert ;
  • stay compositionend Incident , It contains all the input in this synthesis process .

Similar to text events , Composite events can be used to filter input if necessary . You can use composite events as follows :

let textbox = document.getElementById("text");
textbox.addEventListener("compositionstart", (event) => {
console.log(event.data);
});
textbox.addEventListener("compositionupdate", (event) => {
console.log(event.data);
});
textbox.addEventListener("compositionend", (event) => {
console.log(event.data);
})

In addition to the above event types ,DOM2 The event of change (Mutation Events) By Mutation Observers replace . There are also device events used to define devices and device related 、 Touch events for touch devices , And resource events and so on , Not one by one .

Custom events

DOM3 Added custom event type . Custom events do not trigger native DOM event , But you can create new event types , Use document.createEvent(type) Create event types ,type Is a string , Represents the type of event created . Such as "UIEvents""MouseEvents" etc. . Create custom events , You need to pass in "CustomEvent".

After creating the event , Need to call initCustomEvent() Initialize the event , This method receives 4 Parameters .

  • type: Indicates the type of event to trigger , Return string , Such as "customEvent".
  • bubbles: Indicates whether the event is bubbling , Returns a Boolean value .
  • cancelable: Indicates whether the event can be cancelled , Returns a Boolean value .
  • detail: Represents any value , As event Object's detail attribute . Returns the object .

Custom events can be used in the same way as other events DOM In the middle . Such as :

<div id="div" value="Dom Custom Event Handler">DOM Custom Event Handler</div>
<script>
let div = document.getElementById("div");
div.addEventListener("cusEvent", (event) => {
console.log("DIV: " + event.detail);
});
document.addEventListener("cusEvent", (event) => {
console.log("DOCUMENT: " + event.detail);
});
let event = document.createEvent("CustomEvent");
event.initCustomEvent("cusEvent", true, false, "Custom Event");
div.dispatchEvent(event);
</script>

stay initCustomEvent The second parameter is set to bubble , So the browser is responsible for bubbling events to document.

DOM4 Added right CustomEvent Constructor support , have access to new CustomEvent(type, eventInitDict) To create custom events . It has the following parameters .

  • type: Type of event , Is a string .
  • eventInitDict: An object , Provides configuration information for events .

and eventInitDict The type of the parameter is CustomEventInit, It has several parameters .

  • bubbles: A Boolean value , Indicates whether the event will bubble .
  • cancelable: A Boolean value , Indicates whether the event can be cancelled .
  • detail: Data passed when an event is initialized .

For example :

<div id="div" value="Dom Custom Event Handler">DOM Custom Event Handler</div>
<script>
let div = document.getElementById("div");
div.addEventListener("cusEvent", (event) => {
console.log("DIV: " + event.detail);
});
document.addEventListener("cusEvent", (event) => {
console.log("DOCUMENT: " + event.detail);
});
let event = new CustomEvent("cusEvent", {detail: {name: " David "}, bubbles: true});
div.dispatchEvent(event);
</script>

Event delegation

Event delegation takes advantage of event bubbling , Use an event handler to manage events of the same type .

<ul id="links">
<li id="red">Red</li>
<li id="green">Green</li>
<li id="blue">Blue</li>
</ul>

Usually to <li> Element to add click events , Usually three <li> The elements are assigned three onclick The handler . Not so much , We can do it in <ul> Element to capture all of the <li> Click event of element :

let list = document.getElementById('links');
list.addEventListener("click", (event) => {
let target = event.target;
switch (target.id) {
case "red":
document.title = " in the limelight ";
break;
case "green":
location.href = "http://www.sample.com";
break;
case "blue":
alert("Hi, Blue");
break;
}
});

such , Click on each <li> Elements , Will bubble things up , Give it to the parent node <ul> To handle , stay <ul> In the event , adopt event.target Of id Attribute to determine which element was clicked , Then perform the corresponding operation .

Event delegation has the following advantages :

  • document Objects are always available , You can add event handlers to it at any time . This means that as long as the page renders clickable elements , It works without delay .
  • Save time on setting up page event handlers . Specifying only one event handler saves DOM quote , It can also save time .
  • Reduce the memory required for the entire page , Improve overall performance .

You can delete the event handler first , Through innerHTML Attribute to DOM Delete operation , To remove unused event handlers , To improve the Web application performance .

<div id="div">
<input id="btn" type="button" value="Del Event Handler">
</div>
<script>
let btn = document.getElementById("btn");
btn.onclick = function () {
// Perform the operation
...
btn.onclick = null; // Delete event handler
document.getElementById("div").innerHTML = "Processing...";
}
</script>

Summary

Event is JavaScript The main way to interact with a web page .、 This paper mainly introduces the receiving sequence of events , Event objects and common event types , There are also some event types such as HTML5 event 、 Device events and so on are not introduced , Some browsers also implement their own proprietary Events , It is convenient to expand the functions to meet the needs of users . The incident happened in JavaScript It's very important , Understanding how events work is also important to their performance .


More content please pay attention to the public number 「 Sea people's blog 」, reply 「 resources 」 Free learning resources are available !

image

版权声明
本文为[hireny]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210124115156821b.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云