Javascript事件:捕获,目标,气泡

Javascript事件和事件处理: (Javascript events and event handling:)

Events are actions occurring on a webpage due to various types of interaction from the user. These include interactions such as mouse click, keypress, scroll, resize, etc. The user interactions are usually performed on an HTML element, and when any type of interaction is performed, an event is fired. This event will simply follow its life cycle(event propagation) unless an event-handler is registered to perform any operation in response to the event.

事件是由于来自用户的各种类型的交互而在网页上发生的动作。 这些交互包括鼠标单击,按键,滚动,调整大小等交互。用户交互通常在HTML元素上执行,并且当执行任何类型的交互时,都会触发事件。 除非注册了事件处理程序以响应该事件执行任何操作,否则该事件将仅遵循其生命周期(事件传播)。

The standard DOM Events has 3 phases of event propagation:

标准DOM事件具有事件传播的3个阶段:

  • Event Capturing phase: the event goes down to the element.

    事件捕获阶段 :事件进入元素。

  • Event Target phase: the event has reached the element.

    事件目标阶段:事件已到达元素。

  • Event Bubbling phase: the event is bubbled up from the element.

    事件冒泡阶段 :事件从元素冒泡。

Note that not every DOM event bubbles up. There are some exceptions to this. The focus event doesn't bubble up the DOM tree.

请注意,并非每个DOM事件都会冒泡。 这有一些例外。 focus事件不会使DOM树冒泡。

In this article, we will understand the life cycle of the events, the execution phase of event handlers, and how to manipulate default browser behavior when an event is fired.

在本文中,我们将了解事件的生命周期,事件处理程序的执行阶段,以及触发事件时如何操作默认浏览器行为。

事件捕捉 (Event Capture)

Event capture is the first phase of event propagation when a user interaction happens in the browser. In this phase, the user event propagates down the DOM tree until it reaches the target node which generated the event. During this phase, the event is transferred through the DOM chain passing through every node which is the parent of the target event.

当用户在浏览器中发生交互时,事件捕获是事件传播的第一阶段。 在此阶段,用户事件沿DOM树向下传播,直到到达生成事件的目标节点为止。 在此阶段中,事件通过DOM链传递,该DOM链穿过作为目标事件父级的每个节点。

Generally, when event handlers are added to HTML code, they are not triggered during the event capture phase unless it is explicitly specified. We can do this while registering an event handler. Consider the follow code:

通常,将事件处理程序添加到HTML代码时,除非明确指定,否则它们不会在事件捕获阶段触发。 我们可以在注册事件处理程序时执行此操作。 考虑以下代码:

<div id="div1">
<button id="button1"></button>
</div>const divElement = document.getElementById("div1");
const buttonElement = document.getElementById("button1");
divElement.addEventListener(<eventname>, <callback>, {capture: true});

The following piece of code will fire the callback function during the event capture phase. This means that the callback function is executed even before the event has reached the buttonElement.

以下代码段将在事件捕获阶段触发回调函数。 这意味着即使在事件到达buttonElement之前,也会执行回调函数。

活动目标 (Event Target)

The event.target is the innermost DOM element which caused the event to be fired. Since an event is captured and bubbled up, it is important to know the value event.target holds.

event.target是导致事件被触发的最里面的DOM元素。 由于事件被捕获并冒泡,因此了解event.target的值很重要。

In javascript, an event is also an object which is propagated through the DOM tree. This object holds 2 important values:

在javascript中,事件也是通过DOM树传播的对象。 该对象具有两个重要值:

  1. event.target: This is the target element that caused the event. Its value doesn't change no matter where in the DOM tree the event resides currently.

    event.target :这是导致事件的目标元素。 无论事件当前在DOM树中的何处,其值都不会改变。

  2. event.currentTarget/ this: This is the element that currently contains the event. It can be either the during capture phase or bubble phase. It's value changes based on which element is currently having the event in possession.

    event.currentTarget / this :这是当前包含事件的元素。 它可以是捕获阶段或气泡阶段。 它的值根据当前拥有事件的元素而变化。

source

资源

事件冒泡 (Event Bubbling)

Once the event has reached its target( event.target), the same event starts bubbling up the DOM tree. Any event handlers attached to the event will be now triggered by default. Note that, all the event handlers attached to the elements in the DOM tree will be triggered.

一旦事件达到其目标( event.target ),则同一事件开始冒泡DOM树。 现在,默认情况下将触发附加到该事件的任何事件处理程序。 请注意,将触发所有附加到DOM树中元素的事件处理程序。

const divElement = document.getElementById("div1");
const buttonElement = document.getElementById("button1");
divElement.addEventListener(<eventname>, <callback2>);
buttonElement.addEventListener(<eventname>, <callback1>);

When the corresponding event attached to the listeners is triggered, both the callback functions will be executed in the following order: 1. callback1 2. callback2

当触发附加到侦听器的相应事件时,两个回调函数将按以下顺序执行:1. callback1 2. callback2

To sum up, the whole flow of event propagation, consider the following code:

总结一下,事件传播的整个流程,请考虑以下代码:

const divElement = document.getElementById("div1");
const buttonElement = document.getElementById("button1");
divElement.addEventListener("click", alert(Capture: Div), {capture: true});
buttonElement.addEventListener("click", alert(Capture: Button), {capture: true})
divElement.addEventListener("click", alert(Bubble: Div));
buttonElement.addEventListener("click", alert(Capture: Button));

When the click event is fired on the button, the following alerts are fired in the given order:

按钮上触发click事件时,将以给定的顺序触发以下警报:

  1. alert(Capture: Div)

    警报(捕获:Div)

  2. alert(Capture: Button)

    警报(捕获:按钮)

  3. alert(Bubble: Button)

    警报(气泡:按钮)

  4. alert(Bubble: Div)

    警报(气泡:div)

Note that, the event is only propagated until the target element which caused the event to be fired. If the user clicked on the div instead of button, only the event handlers attached to the div will be executed, in the following order:

请注意,事件仅传播到导致事件触发的目标元素为止。 如果用户单击div而不是button ,则将仅按以下顺序执行附加到div的事件处理程序:

  1. alert(Capture: Div)

    警报(捕获:Div)

  2. alert(Bubble: Div)

    警报(气泡:div)

覆盖浏览器默认值 (Overriding browser defaults)

The default behavior of the event lifecycle includes capture, target, and bubble-up, however, these behaviors can be overridden with the builtin methods given by javascript.

事件生命周期的默认行为包括捕获,目标和冒泡,但是,可以使用javascript提供的内置方法来覆盖这些行为。

  • stopPropagation(): event.stopPropagation() will stop the event from bubbling up the DOM tree. When one of the child elements handling the event uses stopPropagation, the event stops and the parent element will no longer handle the event. stopPropagation while useful, can be a double-edged sword. Sometimes events such as load are fired at the page level, and it is good not to stop its propagation.

    stopPropagation()event.stopPropagation()将阻止事件冒泡DOM树。 当处理事件的子元素之一使用stopPropagation ,事件将停止,父元素将不再处理该事件。 stopPropagation虽然有用,但可以是一把双刃剑。 有时,在页面级别会触发诸如load类的事件,因此最好不要停止其传播。

const divElement = document.getElementById("div1");
const buttonElement = document.getElementById("button1");
divElement.addEventListener("click", alert(Bubble: Div));
buttonElement.addEventListener("click", function(e){
alert(Capture: Button));
e.stopPropagation();
}

Since stopPropagation() is used, only alert(Bubble: Button) method will be executed.

由于使用了stopPropagation() ,因此将仅执行alert(Bubble:Button)方法。

  • stopImmediatePropagation(): If multiple event handlers are attached to the same event, the handlers are called in the order in which they are registered. event.stopImmediatePropagation() prevents other listeners of the same event from being called.

    stopImmediatePropagation() :如果将多个事件处理程序附加到同一事件,则将按注册它们的顺序调用这些处理程序。 event.stopImmediatePropagation()防止调用同一事件的其他侦听器。

  • preventDefault(): Certain events like radio/checkbox clicks, input keypress, performs default action. event.preventDefault() will stop the default behavior. This is generally used to build controlled forms in libraries such as ReactJS

    preventDefault() :某些事件(例如单选按钮/复选框单击,输入按键按下)执行默认操作。 event.preventDefault()将停止默认行为。 通常用于在ReactJS等库中构建受控表格

<form>
<label for="checkbox1">Checkbox:</label>
<input type="checkbox" id="checkbox1"/>
</form>const checkBoxElement = document.getElementById("checkbox1");
checkBoxElement.addEventListener("click", function(e){
e.preventDefault();
}

In the above example, event.preventDefault() will prevent the checkbox from even being in checked state by user clicks. PreventDefault works only if the event is cancelable, to check whether an event is cancelable, use event.cancelable

在上面的示例中, event.preventDefault()将阻止复选框甚至通过用户单击而处于checked状态。 PreventDefault仅在事件可取消时才有效,要检查事件是否可取消,请使用event.cancelable

It is important to understand the direction, timing, and purpose of events to perform better event handling in webpages. I hope this article provided all the information you needed regarding event propagation.

重要的是要了解事件的方向,时间和目的,以便在网页中执行更好的事件处理。 我希望本文能提供您所需的有关事件传播的所有信息。

Originally published at https://aparnajoshi.netlify.app.

最初发布在 https://aparnajoshi.netlify.app上

翻译自: https://medium.com/swlh/javascript-events-capture-target-bubble-7e76363884e9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值