Table of Contents
1. Events
2. Event flow
Home Web Front-end Front-end Q&A What are the event streams in javascript?

What are the event streams in javascript?

Jan 26, 2022 pm 01:02 PM
javascript

The event streams of JavaScript are: 1. Bubbling event stream, the propagation of events is from the most specific event target to the least specific event target; 2. Capture type event stream, the propagation of events is from From the least specific event target to the most specific event target; 3. DOM event flow.

What are the event streams in javascript?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

1. Events

An event is a specific interaction moment that occurs in a document or browser window.

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 are: 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

The event flow describes the order in which events are received from the page.

1. Event awareness

Question: Click on a page element, what kind of element Can you 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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

<!DOCTYPE html>

<html>

<head>

    <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>

<div id="outer">

   <div id="middle">

        <div id="inner">

            click me!

        </div>

    </div>

</div>

<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 between the element node and the root node in a specific order. All nodes along the path will receive the event. This propagation process is the DOM event stream.

1), two event flow models

The order of event propagation corresponds to the two event flow models of the browser: capture event flow and bubbling event streams.

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. [Recommended]

Captured event stream: The propagation of events is from the least specific's event target to the most specific event target . That is, from the root of the DOM tree to the leaves.

The idea of ​​event capture is that less specific nodes should receive events earlier, and the most specific nodes should receive events last.

1

2

3

4

5

6

7

8

9

10

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title></title>

</head>

<body>

<div id="myDiv">Click me!</div>

</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

click in the capture event stream The order of event propagation is document—》—》—》

note:

1)、所有现代浏览器都支持事件冒泡,但在具体实现中略有差别:

IE5.5及更早版本中事件冒泡会跳过元素(从body直接跳到document)。

IE9、Firefox、Chrome、和Safari则将事件一直冒泡到window对象。

2)、IE9、Firefox、Chrome、Opera、和Safari都支持事件捕获。尽管DOM标准要求事件应该从document对象开始传播,但这些浏览器都是从window对象开始捕获事件的。

3)、由于老版本浏览器不支持,很少有人使用事件捕获。建议使用事件冒泡

2)、DOM事件流

DOM标准采用捕获+冒泡。两种事件流都会触发DOM的所有对象,从document对象开始,也在document对象结束。

DOM标准规定事件流包括三个阶段:事件捕获阶段、处于目标阶段和事件冒泡阶段。

  • 事件捕获阶段:实际目标

    )在捕获阶段不会接收事件。也就是在捕获阶段,事件从document到再到就停止了。上图中为1~3.

  • 处于目标阶段:事件在

    上发生并处理。但是事件处理会被看成是冒泡阶段的一部分

  • 冒泡阶段:事件又传播回文档。

note:

1)、尽管“DOM2级事件”标准规范明确规定事件捕获阶段不会涉及事件目标,但是在IE9、Safari、Chrome、Firefox和Opera9.5及更高版本都会在捕获阶段触发事件对象上的事件。结果,就是有两次机会在目标对象上面操作事件。

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

<!DOCTYPE html>

<html>

<head>

    <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>

<div id="outer">

    <div id="middle">

        <div id="inner">

            click me!

        </div>

    </div>

</div>

<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事件代理则是一种简单有效的技巧,通过它可以把事件处理器添加到一个父级元素上,从而避免把事件处理器添加到多个子级元素上。

1)、事件代理

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<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

2)、事件代理的好处

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

  • 将多个事件处理器减少到一个,因为事件处理器要驻留内存,这样就提高了性能。想象如果有一个100行的表格,对比传统的为每个单元格绑定事件处理器的方式和事件代理(即table上添加一个事件处理器),不难得出结论,事件代理确实避免了一些潜在的风险,提高了性能。
  • DOM更新无需重新绑定事件处理器,因为事件代理对不同子元素可采用不同处理方法。如果新增其他子元素(a,span,p等),直接修改事件代理的事件处理函数即可,不需要重新绑定处理器,不需要再次循环遍历。

3)、事件代理的问题:【update20170502】

代码如下:事件代理同时绑定了li和span,当点击span的时候,li和span都会冒泡。

1

2

3

4

5

6

7

8

9

10

11

<li><span>li中的span的内容</span></li>

 

<script>

    $(document).on(&#39;click&#39;, &#39;li&#39;, function(e){

        alert(&#39;li li&#39;);

    });

 

    $(document).on(&#39;click&#39;, &#39;span&#39;, function(e){

        alert(&#39;li span&#39;);

    })

</script>

Copy after login

解决办法:

方法一:span的事件处理程序中阻止冒泡

1

2

3

4

$(document).on(&#39;click&#39;, &#39;span&#39;, function(e){

       alert(&#39;li span&#39;);

       e.stopPropagation();

   })

Copy after login

方法二:li的事件处理程序中检测target元素

1

2

3

4

5

6

7

$(document).on(&#39;click&#39;, &#39;li&#39;, function (e) {

        if (e.target.nodeName == &#39;SPAN&#39;) {

            e.stopPropagation();

            return;

        }

        alert(&#39;li li&#39;);

    });

Copy after login

4)、事件代理的一个有趣应用【update20170502】

点击一个列表时,输出对应的索引

1

2

3

4

5

6

7

8

9

10

<script>

    var ul=document.querySelector(&#39;ul&#39;);

    var lis=ul.querySelectorAll(&#39;ul li&#39;);

    ul.addEventListener(&#39;click&#39;, function (e) {

        var target= e.target;

        if(target.nodeName.toUpperCase()===&#39;LI&#39;){

            alert([].indexOf.call(lis,target));

        }

    },false)

</script>

Copy after login

【相关推荐:javascript学习教程

The above is the detailed content of What are the event streams in javascript?. 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
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 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
1665
14
PHP Tutorial
1270
29
C# Tutorial
1250
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles