简体   繁体   English

当孩子停止传播时如何听孩子的事件

[英]How to listen children's events when children stop propagation

I need to watch children's events in Document level, but if the children stop propagation by using method stopPropagation() , I cannot listen those events occur in children. 我需要在“ Document级别观看孩子的事件,但是如果孩子通过使用stopPropagation()方法停止传播,我将无法收听那些发生在孩子中的事件。

Can someone know a better way to do this? 有人知道更好的方法吗?


EDIT: now I want to create an chrome extension to monitor DOM node event, but the event could be stopped propagation, and it is not a good practice to add extra listener to all nodes. 编辑:现在我想创建一个chrome扩展来监视DOM节点事件,但是该事件可以停止传播,并且不是向所有节点添加额外的侦听器的好习惯。 Following example will show my question. 以下示例将显示我的问题。

customer HTML fragment 客户HTML片段

<body>
  <input type="button" value="Click Me" id="b">
</body>

customer javascript 客户javascript

var button = document.querySelector('#b');
button.addEventListener('click', function(e) {
  console.log('Button has been clicked');
  e.stopPropagation();
});

chrome extension content scripts chrome扩展程序内容脚本

document.addEventListener('click', function(e) {
  console.log('Node(' + e.target.nodeName + ') has been clicked');
  // this listener will not be invoked because event has been stopped
  // propagation.
});

You can use "capturing" to track an event before bubbling. 您可以在冒泡之前使用“捕获”来跟踪事件。 There's a very good description of how capturing works (as contrasted with bubbling) in this article: Bubbling and capturing . 本文对捕获的工作原理进行了很好的描述(与冒泡相比): 冒泡和捕获

In summary, all browsers except IE before IE9, send events down the chain to the leaf where the event occurred and then they bubble the events back up. 总之,除IE9之前的IE之外,所有其他浏览器都将事件沿链向下发送到事件发生的叶子,然后使事件冒泡。 Normal event listening only listens for the event on the actual object or for propagated events, but if you set the third argument to .addEventListener() to true, then it will also listen to events going down the chain where the document object will see the event FIRST before bubbling has even started or been cancelled. 普通事件侦听仅侦听实际对象上的事件或传播的事件,但是如果将.addEventListener()的第三个参数设置为true,则它还将侦听document对象将看到的事件链中的事件。在冒泡甚至开始或被取消之前的事件FIRST。

Here's a working snippet demo: 这是一个工作片段演示:

 // show output function log(x) { var div = document.createElement("div"); div.innerHTML = x; document.body.appendChild(div); } // stop propagation on leaf click var leaf = document.getElementById("leaf"); leaf.addEventListener("click", function(e) { log("leaf message - click in leaf, propagation stopped") e.stopPropagation(); }, false); // capture listen document.addEventListener("click", function(e) { if (e.target === leaf) { log("document message - click in leaf"); } }, true); 
 <div id="topParent"> <div id="midParent"> <div id="leaf"> Click Here </div> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM