Home Web Front-end JS Tutorial How much do you know about JavaScript event streams? You will know after reading this article

How much do you know about JavaScript event streams? You will know after reading this article

Jul 26, 2018 am 11:51 AM
js event

Event flu awareness: Question: When you click on a page element, what kind of element can sense such an event? Answer: When you click on an element, you also click on the container element of the element, or even the entire page. This article mainly introduces the relevant information about the JavaScript event learning summary. Friends who need it can refer to it

1. Event

An event is a certain action performed by the user or the browser itself, such as click, load and mouseover are the names of the events.

Events are the bridge between javaScript and DOM.

If you trigger it, I will execute it - when the event occurs, its handler function is called to execute the corresponding JavaScript code to give a response.

Typical examples include: the load event is triggered when the page is loaded; the click event is triggered when the user clicks on an element.

2. Event flow

1. Event flu understanding

Question: Click Page elements, what kind of elements can sense such an event?

Answer: When you click on an element, you also click on the container element of the element, or even the entire page.

Example: There are three concentric circles. Add the corresponding event processing function to each circle and pop up the corresponding text. When you click the innermost circle, you also click the outer circle, so the click event of the outer circle will also be triggered.

<!DOCTYPE html>
<html>
<head lang="en">
 <meta charset="UTF-8">
 <title></title>
</head>
<style>
 #outer{
 position: absolute;
 width: 400px;
 height: 400px;
 top:0;
 left: 0;
 bottom:0;
 right: 0;
 margin: auto;
 background-color: deeppink;
 }
 #middle{
 position: absolute;
 width: 300px;
 height:300px;
 top:50%;
 left: 50%;
 margin-left: -150px;
 margin-top: -150px;
 background-color: deepskyblue;
 }
 #inner{
 position: absolute;
 width: 100px;
 height:100px;
 top:50%;
 left:50%;
 margin-left: -50px;
 margin-top: -50px;;
 background-color: darkgreen;
 text-align: center;
 line-height: 100px;
 color:white;
 }
 #outer,#middle,#inner{
border-radius:100%;
 }
</style>
<body>
<p id="outer">
 <p id="middle">
 <p id="inner">
 click me!
 </p>
 </p>
</p>
<script>
 var innerCircle= document.getElementById("inner");
 innerCircle.onclick= function () {
 alert("innerCircle");
 };
 var middleCircle= document.getElementById("middle");
 middleCircle.onclick=function(){
 alert("middleCircle");
 }
 var outerCircle= document.getElementById("outer");
 outerCircle.onclick= function () {
 alert("outerCircle");
 }
</script>
</body>
</html>
Copy after login

The effect is as follows:

2. Event flow

When an event occurs, it will be propagated in a specific order between the element node and the root node. All nodes along the path will receive the event. This propagation process is the DOM event stream.

The order of event propagation corresponds to the browser's two event flow models: capturing event flow and bubbling event flow.

Bubble-type event flow: The propagation of events is from the most specific event target to the least specific event target. That is, from the leaves of the DOM tree to the root.

Capture event flow: The propagation of events is from the least specific event target to the most specific event target. That is, from the root of the DOM tree to the leaves.

<!DOCTYPE html>
<html>
<head lang="en">
 <meta charset="UTF-8">
 <title></title>
</head>
<body>
<p id="myp">Click me!</p>
</body>
</html>
Copy after login

In the above HTML code, the

element in the page is clicked.

The order of click event propagation in the bubbling event stream is

—》 —》—》document

In the capture event stream, the order of click event propagation is document—》—》—》

note:

1), all modern browsers support event bubbling, but there are slight differences in the specific implementation. Difference:

Event bubbling in IE5.5 and earlier versions will skip the element (jump directly from body to document).

IE9, Firefox, Chrome, and Safari bubble the event all the way to the window object.

2), IE9, Firefox, Chrome, Opera, and Safari all support event capture. Although the DOM standard requires that events should be propagated from the document object, these browsers capture events from the window object.

3). Since old versions of browsers do not support it, few people use event capture. It is recommended to use event bubbling.

DOM event flow

The DOM standard uses capture bubbling. Both event streams will trigger all objects in the DOM, starting with and ending with the document object.

The DOM standard stipulates that the event flow includes three stages: the event capture stage, the target stage and the event bubbling stage.

Event capture phase: The actual target (

) will not receive events during the capture phase. That is, during the capture phase, the event stops from document to to . In the picture above, it is 1~3.

is in the target stage: events occur and are processed on

. But event handling is considered part of the bubbling phase.

Bubbling phase: The event is propagated back to the document.

note:

1): The DOM standard stipulates that event capture phase capture involves event targets, but in IE9, Safari, Chrome, Firefox and Opera9.5 and higher Both versions will fire events on the event object during the capture phase. The result is that there are two opportunities to operate events on the target object.

2):并非所有的事件都会经过冒泡阶段 。所有的事件都要经过捕获阶段和处于目标阶段,但是有些事件会跳过冒泡阶段:如,获得输入焦点的focus事件和失去输入焦点的blur事件。

两次机会在目标对象上面操作事件例子:

<!DOCTYPE html>
<html>
<head lang="en">
 <meta charset="UTF-8">
 <title></title>
</head>
<style>
 #outer{
 position: absolute;
 width: 400px;
 height: 400px;
 top:0;
 left: 0;
 bottom:0;
 right: 0;
 margin: auto;
 background-color: deeppink;
 }
 #middle{
 position: absolute;
 width: 300px;
 height:300px;
 top:50%;
 left: 50%;
 margin-left: -150px;
 margin-top: -150px;
 background-color: deepskyblue;
 }
 #inner{
 position: absolute;
 width: 100px;
 height:100px;
 top:50%;
 left:50%;
 margin-left: -50px;
 margin-top: -50px;;
 background-color: darkgreen;
 text-align: center;
 line-height: 100px;
 color:white;
 }
 #outer,#middle,#inner{
 border-radius:100%;
 }
</style>
<body>
<p id="outer">
 <p id="middle">
 <p id="inner">
 click me!
 </p>
 </p>
</p>
<script>
 var innerCircle= document.getElementById("inner");
 innerCircle.addEventListener("click", function () {
 alert("innerCircle的click事件在捕获阶段被触发");
 },true);
 innerCircle.addEventListener("click", function () {
 alert("innerCircle的click事件在冒泡阶段被触发");
 },false);
 var middleCircle= document.getElementById("middle");
 middleCircle.addEventListener("click", function () {
 alert("middleCircle的click事件在捕获阶段被触发");
 },true);
 middleCircle.addEventListener("click", function () {
 alert("middleCircle的click事件在冒泡阶段被触发");
 },false);
 var outerCircle= document.getElementById("outer");
 outerCircle.addEventListener("click", function () {
 alert("outerCircle的click事件在捕获阶段被触发");
 },true);
 outerCircle.addEventListener("click", function () {
 alert("outerCircle的click事件在冒泡阶段被触发");
 },false);
</script>
</body>
</html>
Copy after login

运行效果就是会陆续弹出6个框,为说明原理我整合成了一个图:

3、事件流的典型应用——事件代理

传统的事件处理中,需要为每个元素添加事件处理器。js事件代理则是一种简单有效的技巧,通过它可以把事件处理器添加到一个父级元素上,从而避免把事件处理器添加到多个子级元素上。

事件代理的原理用到的就是事件冒泡和目标元素,把事件处理器添加到父元素,等待子元素事件冒泡,并且父元素能够通过target(IE为srcElement)判断是哪个子元素,从而做相应处理。关于target更多内容请参考javaScript事件学习小结(四)event的公共成员(属性和方法)下面举例来说明。

传统事件处理,为每个元素添加事件处理器,代码如下:

<body>
<ul id="color-list">
<li>red</li>
<li>orange</li>
<li>yellow</li>
<li>green</li>
<li>blue</li>
<li>indigo</li>
<li>purple</li>
</ul>
<script>
(function(){
 var colorList=document.getElementById("color-list");
 var colors=colorList.getElementsByTagName("li");
 for(var i=0;i<colors.length;i++)
 {
 colors[i].addEventListener(&#39;click&#39;,showColor,false);
 };
 function showColor(e)
 {
 e=e||window.event;
 var targetElement=e.target||e.srcElement;
 alert(targetElement.innerHTML);
 }
})();
</script>
</body>
Copy after login

事件代理的处理方式,代码如下:

<body>
<ul id="color-list">
<li>red</li>
<li>orange</li>
<li>yellow</li>
<li>green</li>
<li>blue</li>
<li>indigo</li>
<li>purple</li>
</ul>
<script>
(function(){
 var colorList=document.getElementById("color-list");
 colorList.addEventListener(&#39;click&#39;,showColor,false);
 function showColor(e)
 {
 e=e||window.event;
 var targetElement=e.target||e.srcElement;
 if(targetElement.nodeName.toLowerCase()==="li"){
 alert(targetElement.innerHTML);
 }
 }
})();
</script>
</body>
Copy after login

总结一下事件代理的好处:

a、将多个事件处理器减少到一个,因为事件处理器要驻留内存,这样就提高了性能。想象如果有一个100行的表格,对比传统的为每个单元格绑定事件处理器的方式和事件代理(即table上添加一个事件处理器),不难得出结论,事件代理确实避免了一些潜在的风险,提高了性能。

b、DOM更新无需重新绑定事件处理器,因为事件代理对不同子元素可采用不同处理方法。如果新增其他子元素(a,span,p等),直接修改事件代理的事件处理函数即可,不需要重新绑定处理器,不需要再次循环遍历。

以上所述是小编给大家介绍的JavaScript事件学习小结(一)事件流的相关知识,希望对大家有所帮助!

相关推荐:

The above is the detailed content of How much do you know about JavaScript event streams? You will know after reading this article. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

Python vs. JavaScript: Use Cases and Applications Compared Python vs. JavaScript: Use Cases and Applications Compared Apr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles