Javascript 简明教程

JavaScript - Event Capturing

Event Capturing

JavaScript 中的事件捕获是事件传播模型中的初始阶段,其中事件从文档树的根部向下传输到目标元素。在此阶段,浏览器捕获目标元素祖先处的事件,然后才能到达目标元素本身。

Event capturing in JavaScript is the initial phase in the event propagation model where the event travels from the root of the document tree down to the target element. During this phase, the browser captures the event on the ancestors of the target element before reaching the target itself.

事件捕获和事件冒泡是 JavaScript 事件传播模型中的两个阶段。在事件捕获中,浏览器从文档层次的根部开始捕获和触发事件,并且向下传输到目标元素。另一方面,事件冒泡发生在事件到达目标元素之后,然后从目标向上冒泡到根部。

Event capturing and event bubbling are two phases in the JavaScript event propagation model. In event capturing, the browser captures and triggers events starting from the root of the document hierarchy and moving down to the target element. On the other hand, event bubbling occurs after the event reaches the target element and then bubbles up from the target to the root.

捕获对于在更高级别的祖先处处理事件很有用,而冒泡是事件从目标向上传播层次结构的默认行为。理解这两个阶段对于有效处理事件和操纵事件流非常重要。

Capturing is useful for handling events at higher-level ancestors, while bubbling is the default behaviour where events propagate from the target back up the hierarchy. Understanding both phases is crucial for effective event handling and manipulation of the event flow.

让我们看看事件捕获的一些重要方面。

Let us see some important aspects of event capturing.

Aspect

Description

Phase

Event capturing is the initial phase in the event propagation model.

Direction

Capturing occurs in the reverse order of the element hierarchy, from the root of the document tree down to the target element.

Use Case

Useful when you want to intercept and handle events at a higher-level ancestor before they reach the target element or trigger any bubbling phase handlers.

Registration

Register event listeners for the capturing phase using the third parameter of addEventListener (e.g., element.addEventListener('click', myFunction, true);).

Propagation

Automatic propagation that precedes the target and bubbling phases. The event flows down the hierarchy, triggering capturing phase handlers on each ancestor.

Preventing Default

Use event.preventDefault() during the capturing phase to prevent the default behavior of the event before it reaches the target.

Stopping Propagation

Use event.stopPropagation() in the capturing phase to stop further propagation of the event, preventing it from reaching the target or triggering bubbling phase handlers.

Example: Basic Event Capturing

在此示例中,我们在其中有一个容器 div (container) 和一个按钮 (myButton)。使用具有 true 参数的 addEventListener 添加了两个捕获阶段事件监听器以启用捕获。当你单击该按钮时,两个捕获阶段日志消息(已单击容器和已单击按钮)将会显示。这说明了捕获阶段,因为事件从文档根部向下传输到目标元素。

In this example, we have a container div (container) and a button (myButton) inside it. Two capturing phase event listeners are added using addEventListener with the true parameter to enable capturing. When you click the button, both capturing phase log messages (Container clicked and Button clicked) will be displayed. This illustrates the capturing phase as the event travels from the document root down to the target element.

<!DOCTYPE html>
<html>
<body>
	<div id="container">
		<button id="myButton">Click me!</button>
	</div>
	<div id = "output"></div>
	<script>
		const output = document.getElementById('output');
		document.getElementById('container').addEventListener('click', function(event) {
			output.innerHTML += 'Capturing phase - Container clicked' + "<br>";
		}, true);

		document.getElementById('myButton').addEventListener('click', function(event) {
			output.innerHTML += 'Capturing phase - Button clicked' + "<br>";
		}, true);
	</script>
</body>
</html>

Example: Preventing Default Behaviour

在此示例中,我们有一个具有 id 为“link”的超链接 (<a>)。在捕获阶段,捕获阶段事件监听器附加到了该链接。当你单击该链接时,捕获阶段日志消息(已单击链接)将会显示,并且使用 event.preventDefault() 阻止了默认行为(导航到新页面)。

In this example, we have a hyperlink (<a>) with an id of "link". The capturing phase event listener is attached to the link during the capturing phase. When you click the link, the capturing phase log message (Link clicked) will be displayed, and the default behaviour (navigating to a new page) is prevented using event.preventDefault().

如果没有使用 .preventDefault(),它本会将页面导航到 [role="bare"] [role="bare"]https://www.tutorialspoint.com

If the. preventDefault() was not used, it would have navigated the page to [role="bare"]https://www.tutorialspoint.com.

<!DOCTYPE html>
<html>
<body>
	<a href="https://www.tutorialspoint.com" id="link">Click me to prevent default</a>
	<script>
		document.getElementById('link').addEventListener('click', function(event) {
			alert('Capturing phase - Link clicked');
			event.preventDefault(); // Prevent the default behavior (e.g., navigating to a new page)
		}, true);
	</script>
</body>
</html>

Example: Capturing and Stopping Propagation

在此示例中,父 div 的捕获阶段事件监听器使用 'event.stopPropagation()' 积极阻止了传播。仅当单击按钮时,你才会在捕获阶段期间看到一条日志消息(已单击父项),但是它不会触发子元素捕获阶段内的任何进一步操作。这的确展示了一种在此特定实例中阻止进一步传播的有效方法。

In this example, the parent div’s capturing phase event listener actively halts propagation through the use of 'event.stopPropagation()'. Only upon clicking the button will you see a log message during capture phase ("Parent clicked") being displayed; however, it does not trigger any further action within child elements' capturing phases. This indeed showcases an effective method to arrest additional propagation in this particular instance.

<!DOCTYPE html>
<html>
<body>
	<div id="parent">
		<button id="child">Click me!</button>
	</div>
	<div id = "output"></div>
	<script>
		const output = document.getElementById('output');
		document.getElementById('parent').addEventListener('click', function(event) {
			output.innerHTML += 'Capturing phase - Parent clicked' + "<br>";
			// Stop further propagation to the child element
			event.stopPropagation();
		}, true);
		document.getElementById('child').addEventListener('click', function(event) {
			output.innerHTML += 'Capturing phase - Child clicked' + "<br>";
		}, true);
	</script>
</body>
</html>