目次
What’s the difference between bubbling and capturing?
How do I use capturing or bubbling in practice?
When would I actually need to care about this?
A few things to watch out for
ホームページ ウェブフロントエンド jsチュートリアル DOMでのイベントの泡立ちとキャプチャとは何ですか?

DOMでのイベントの泡立ちとキャプチャとは何ですか?

Jul 02, 2025 am 01:19 AM

事件捕获和冒泡是DOM中事件传播的两个阶段,捕获是从顶层向下到目标元素,冒泡是从目标元素向上传播到顶层。1. 事件捕获通过addEventListener的useCapture参数设为true实现;2. 事件冒泡是默认行为,useCapture设为false或省略;3. 可使用event.stopPropagation()阻止事件传播;4. 冒泡支持事件委托,提高动态内容处理效率;5. 捕获可用于提前拦截事件,如日志记录或错误处理。了解这两个阶段有助于精确控制JavaScript响应用户操作的时机和方式。

What is event bubbling and capturing in the DOM?

So you've heard about event bubbling and capturing in the DOM, but what do they really mean? In short, they're two phases of how events travel through the DOM tree when something happens — like a click or keypress. Understanding them helps you control exactly when and where your JavaScript code responds to user actions.

What’s the difference between bubbling and capturing?

In simple terms:

  • Event capturing is the phase where the event goes from the top of the DOM (like window or document) down to the target element.
  • Event bubbling is the opposite: the event starts at the target element and then "bubbles up" through its parent elements to the top of the document.

Most people are familiar with bubbling because that's usually the default behavior. For example, if you have a <button> inside a <div>, and both have click handlers, clicking the button will first trigger its handler, then the div's, and so on.

How do I use capturing or bubbling in practice?

When you add an event listener using addEventListener, you can specify whether it should run during the capturing phase or the bubbling phase.

Here's the syntax:

element.addEventListener('click', function, useCapture);
  • If useCapture is true, the handler runs during the capturing phase.
  • If false (or omitted), it runs during bubbling.

Let’s say you have this structure:

<div id="outer">
  <button id="inner">Click me</button>
</div>

And this JS:

document.getElementById('outer').addEventListener('click', () => {
  console.log('Outer clicked - bubbling');
}, false);

document.getElementById('outer').addEventListener('click', () => {
  console.log('Outer clicked - capturing');
}, true);

When you click the button, the output would be:

  1. “Outer clicked - capturing” (because capturing happens before bubbling)
  2. Then whatever handler is on the button itself
  3. Then “Outer clicked - bubbling”

This gives you fine-grained control over the order of execution.

When would I actually need to care about this?

You might not always need to think about capturing or bubbling, but here are a few common situations where it matters:

  • Stopping event propagation: Sometimes you don’t want an event to bubble up. For example, if you have a dropdown menu and clicking inside it shouldn't close the menu. Use event.stopPropagation() to stop it from going further.

  • Delegating events: Event bubbling is the reason event delegation works. Instead of attaching a handler to every list item, you can attach one to their container and let events bubble up. This is efficient for dynamic content.

  • Capturing for early interception: Rarely used, but useful in some edge cases. For instance, logging all clicks before they reach the target, or handling errors very early.

A few things to watch out for

  • stopPropagation() affects both phases unless called during capturing.
  • Some events don’t bubble (like focus), so check documentation.
  • Bubbling doesn’t go beyond window; only certain events make it all the way up.
  • The third parameter (useCapture) in addEventListener is easy to forget — but powerful when needed.

基本上就这些.

以上がDOMでのイベントの泡立ちとキャプチャとは何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

ホットトピック

高度なJavaScriptスコープとコンテキスト 高度なJavaScriptスコープとコンテキスト Jul 24, 2025 am 12:42 AM

JavaScriptの範囲は、グローバル、機能、およびブロックレベルの範囲に分割される変数のアクセシビリティ範囲を決定します。コンテキストは、この方向を決定し、関数呼び出し方式に依存します。 1.スコープには、グローバルスコープ(どこでもアクセス可能)、関数スコープ(関数内でのみ有効)、およびブロックレベルのスコープ(letとconstは{}内で有効です)が含まれます。 2。実行コンテキストには、変数オブジェクト、スコープチェーン、およびこの値が含まれます。これは、通常の関数におけるグローバルまたは未定義を指します。メソッドコールはコールオブジェクトを指し、コンストラクターは新しいオブジェクトをポイントし、call/apply/bindで明示的に指定することもできます。 3。閉鎖とは、外部スコープ変数へのアクセスと記憶の関数を指します。それらはしばしばカプセル化とキャッシュに使用されますが、引き起こす可能性があります

Vue 3 CompositionAPI vs. OptionsAPI:詳細な比較 Vue 3 CompositionAPI vs. OptionsAPI:詳細な比較 Jul 25, 2025 am 03:46 AM

VUE3のCompositapiは、複雑なロジックとタイプの導出により適しており、OptionsAPIはシンプルなシナリオや初心者に適しています。 1。OptionsAPIは、データやメソッドなどのオプションに従ってコードを整理し、明確な構造を持っていますが、複雑なコンポーネントは断片化されています。 2。CompusitionAPIは、セットアップを使用して関連ロジックを集中させます。これは、メンテナンスと再利用を助長します。 3。CompusitionAPIは、混合性機能を介して競合のないパラメーター化可能な論理再利用を実現します。これは、混合物よりも優れています。 4。CoputionAPIは、TypeScriptとより正確なタイプの派生をより適切にサポートしています。 5。2つのパフォーマンスとパッケージングのボリュームに大きな違いはありません。 6。

JavaScriptの並行性パターンのマスター:Webワーカーvs. Javaスレッド JavaScriptの並行性パターンのマスター:Webワーカーvs. Javaスレッド Jul 25, 2025 am 04:31 AM

JavaScriptのWebworkersとJavathreadsの同時処理には本質的な違いがあります。 1。JavaScriptは、単一スレッドモデルを採用しています。 Webworkersは、ブラウザによって提供される独立したスレッドです。これは、UIをブロックしないがDOMを操作できない時間のかかるタスクを実行するのに適しています。 2。Javaは、複雑な同時ロジックとサーバー側の処理に適した、スレッドクラスを通じて作成された言語レベルからの実際のマルチスレッドをサポートしています。 3。ウェブワーカーは、PostMessage()を使用してメインスレッドと通信します。これは非常に安全で孤立しています。 Javaスレッドはメモリを共有できるため、同期の問題に注意する必要があります。 4。ウェブワーカーは、画像処理などのフロントエンドの並列コンピューティングにより適しています。

node.jsを使用してCLIツールを構築します node.jsを使用してCLIツールを構築します Jul 24, 2025 am 03:39 AM

プロジェクトを初期化し、package.jsonを作成します。 2。シバンを使用してエントリスクリプトindex.jsを作成します。 3。Package.jsonのBin Fieldsを介してコマンドを登録します。 4. Yargsおよびその他のライブラリを使用して、コマンドラインパラメーターを解析します。 5。NPMLINKローカルテストを使用します。 6.エクスペリエンスを強化するためのヘルプ、バージョン、オプションを追加します。 7.オプションでnpmpublishを介して公開します。 8.オプションでYargsを使用して自動完成を達成します。最後に、合理的な構造とユーザーエクスペリエンスの設計を通じて実用的なCLIツールを作成し、自動化タスクを完了し、ウィジェットを配布し、完全な文で終了します。

JSで要素を作成して追加する方法は? JSで要素を作成して追加する方法は? Jul 25, 2025 am 03:56 AM

document.createelement()を使用して、新しい要素を作成します。 2。TextContent、クラスリスト、SetAttribute、およびその他の方法を使用して要素をカスタマイズします。 3。AppendChild()またはより柔軟なappend()メソッドを使用して、DOMに要素を追加します。 4.オプションで、挿入位置を制御するために、insertbefore()、およびその他のメソッドを使用します。完全なプロセスは、→カスタマイズ→追加を作成することであり、ページコンテンツを動的に更新できます。

TypeScriptの高度な条件付きタイプ TypeScriptの高度な条件付きタイプ Aug 04, 2025 am 06:32 AM

TypeScriptの高度な条件タイプは、TextEndsu?X:Y Syntaxを介してタイプ間の論理的判断を実装します。そのコア機能は、分散条件タイプ、推測タイプの推論、および複雑なタイプのツールの構築に反映されます。 1.条件付きタイプは、裸の型パラメーターに分散され、string [] | number []を取得するためにtoArrayなどのジョイントタイプを自動的に分割できます。 2.分布を使用してフィルタリングおよび抽出ツールを構築します。除外textendsuを除く除外:t、抽出抽出抽出extract textendsu?t:never、およびnullable filters null/undefined。 3

マイクロフロントエンドアーキテクチャ:実用的な実装ガイド マイクロフロントエンドアーキテクチャ:実用的な実装ガイド Aug 02, 2025 am 08:01 AM

MicrofRontendsSolvessCallingChallengesimSimSimSimsByEnablingEndependDevelymentAndDeployment.1)chooseanintegrations trategy:usemodulefederationinwebpack5forruntimeloadingindingindrueindopendence、build-time-integrationforsimplestups、oriframes/webcomponents

javascriptのvar、let、constの違いは何ですか? javascriptのvar、let、constの違いは何ですか? Aug 02, 2025 pm 01:30 PM

varisfunction-scoped、canbereasSigned、hoisted witHedededined、andattachedtotheglobalwindow object;

See all articles