Home Web Front-end JS Tutorial Event bubbling and capturing in JS

Event bubbling and capturing in JS

Nov 07, 2016 pm 05:36 PM
js

刚接触 JS 的那个时候,啥也不懂,只想着如何利用 Google、百度到的函数来解决实际的问题,不会想到去一探究竟。

渐渐的,对 JS 的语言的不断深入,有机会去了解一些原理性东西。最近在看 JQuery 源码,感触很多,总想着用原生的 JS 去实现自己的一个 JQuery 库。说实在的,JQuery 里面很多函数和思路,是千百开源工作者长期的贡献,哪能是短时间就能消化的了。

最近再次碰到 addEventListener函数(MDN 上关于 addEventListener 的介绍,很详细),由于之前并没有弄懂第三个参数的含义,要么默认值,要么手动设置成 false。这次看了不少文章,彻底把事件冒泡和捕获弄懂。

什么事件冒泡与捕获

事件冒泡与捕获是 DOM 中事件传播的两种方式,比如说对于注册了相同事件的两个 DOM 元素(简单点就是两个 div,一里一外),当点击里层 div 的时候,这两个事件谁先执行。

冒泡事件,由里向外,最里层的元素先执行,然后冒泡到外层。

捕获事件,由外向里,最外层的元素先执行,然后传递到内部。

在 IE 9 之前是只支持事件冒泡,IE 9(包括 IE 9) 之后和目前主流的浏览器都同时支持两种事件。

如何设置,只需修改 addEventListener的第三个参数,true 为捕获,false 为冒泡,默认为冒泡。

举个简单的例子,

<div>
  <span class="out">
    <span class="in"></span>
  </span>
</div>
<script type="text/javascript">
  var dom_out = document.getElementsByClassName(&#39;out&#39;)[0];
  var dom_in = document.getElementsByClassName(&#39;in&#39;)[0];
  dom_out.addEventListener(&#39;click&#39;,function(){
    alert(&#39;out&#39;);
  },false);
  dom_in.addEventListener(&#39;click&#39;,function(){
    alert(&#39;in&#39;);
  },false);
</script>
Copy after login

Event bubbling and capturing in JS

在上面这个例子中,事件是按照冒泡来执行的,点击里层的 in,会看到先 alert 的顺序是先 "in" 后 "out",如果把事件改成捕获,alert 的顺序又不一样了。

<script type="text/javascript">
  var dom_out = document.getElementsByClassName(&#39;out&#39;)[0];
  var dom_in = document.getElementsByClassName(&#39;in&#39;)[0];
  dom_out.addEventListener(&#39;click&#39;,function(){
    alert(&#39;out&#39;);
  },true);
  dom_in.addEventListener(&#39;click&#39;,function(){
    alert(&#39;in&#39;);
  },true);
</script>
Copy after login

Event bubbling and capturing in JS

上面这个例子是捕获事件的例子,点击 in效果是不是不一样呢?

之所以会有冒泡和捕获事件(像 IE 9 之前的浏览器不支持捕获事件,还真是反程序员),毕竟在实际中处理事情肯定有个先后顺序,要么由里向外,要么由外向里,两者都是必须的。

但有时候为了兼容 IE 9 以下版本的浏览器,都会把第三个参数设置成 false 或者默认(默认就是 false)。

进一步理解冒泡和捕获

现在已经说清楚冒泡和捕获,那么如果同时出现冒泡和捕获会出现什么结果?

原来浏览器处理时间分为两个阶段,捕获阶段和冒泡阶段,

先执行捕获阶段,如果事件是在捕获阶段执行的(true 情况),则执行;

然后是冒泡阶段,如果事件是在冒泡阶段执行的(false 情况),则执行;

来看一看例子就知道了:

<div>
  <span class="s1">s1
    <span class="s2">s2
      <span class="s3">s3
      </span>
    </span>
  </span>
</div>
Copy after login

这次我们设置三个 span,分别是 s1, s2, s3,然后设置 s1,s3 为冒泡执行,s2 为捕获执行:

<script type="text/javascript">
  var s1 = document.getElementsByClassName(&#39;s1&#39;)[0];
  var s2 = document.getElementsByClassName(&#39;s2&#39;)[0];
  var s3 = document.getElementsByClassName(&#39;s3&#39;)[0];
  s1.addEventListener(&#39;click&#39;,function(){
    alert(&#39;s1&#39;);
  },false);
  s2.addEventListener(&#39;click&#39;,function(){
    alert(&#39;s2&#39;);
  },true);
  s3.addEventListener(&#39;click&#39;,function(){
    alert(&#39;s3&#39;);
  },false);
</script>
Copy after login

Event bubbling and capturing in JS

从运行的效果来看,点击 s3,依次 alert s2 => s3 => s1,说明:

捕获事件和冒泡事件同时存在的,而且捕获事件先执行,冒泡事件后执行;

如果元素存在事件且事件的执行时间与当前逻辑一致(冒泡或捕获),则执行。

默认事件取消与停止冒泡

当然,有时候我们只想执行最内层或最外层的事件,根据内外层关系来把范围更广的事件取消掉(对于新手来说,不取消冒泡,很容易中招的出现 bug)。event.stopPropagation()(IE 中window.event.cancelBubble = true)可以用来取消事件冒泡。

有时候对于浏览器的默认事件也需要取消,这时候用到的函数则是 event.preventDefault()(IE 中window.event.returnValue = false)。

那么默认事件取消和停止冒泡有什么区别呢?我的理解:浏览器的默认事件是指浏览器自己的事件(这不废话吗),比如 a 标签 的点击,表单的提交等,取消掉就不会执行啦;冒泡则取消的是由外向里(捕获)、由里向外(冒泡),stop 之后,就不会继续遍历了。stackoverflow 上的解答

看下例子,依旧是上面那个例子,不过每个函数都加了 停止冒泡:

s1.addEventListener(&#39;click&#39;,function(e){
  e.stopPropagation();
  alert(&#39;s1&#39;);
},false);
s2.addEventListener(&#39;click&#39;,function(e){
  e.stopPropagation();
  alert(&#39;s2&#39;);
},true);
s3.addEventListener(&#39;click&#39;,function(e){
  e.stopPropagation();
  alert(&#39;s3&#39;);
},false);
Copy after login

Event bubbling and capturing in JS

点击的结果是:当点击 s2 或 s3 的时候,都会 alert s2,点击 s1,弹出 s1。因为事件被取消的缘故,点击 s3,执行 s2后就不会在向下执行了。

在看一个 preventDefault 的例子。

<div>
  <a href="/">点我回主页</a>
</div>
<div>
  <a href="/" class="back">点我不回主页</a>
</div>
<script type="text/javascript">
  var back = document.getElementsByClassName(&#39;back&#39;)[0];
  back.addEventListener(&#39;click&#39;, function(e){
    e.preventDefault();
  });
</script>
Copy after login

Event bubbling and capturing in JS

第二个链接是不是回不了主页,因为浏览器的默认事件被取消了。

以上所有例子请在非低版本 IE 浏览器的环境下浏览 O_o

总结

总结就补充两个兼容 IE 的函数吧:

function stopBubble(e) {
  //如果提供了事件对象,则这是一个非IE浏览器
  if ( e && e.stopPropagation )
      //因此它支持W3C的stopPropagation()方法
      e.stopPropagation();
  else
      //否则,我们需要使用IE的方式来取消事件冒泡
      window.event.cancelBubble = true;
}
//阻止浏览器的默认行为
function stopDefault( e ) {
  //阻止默认浏览器动作(W3C)
  if ( e && e.preventDefault )
      e.preventDefault();
  //IE中阻止函数器默认动作的方式
  else
      window.event.returnValue = false;
  return false;
}
Copy after login


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

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function How to use JS and Baidu Maps to implement map polygon drawing function Nov 21, 2023 am 10:53 AM

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file

See all articles