简体   繁体   English

Javascript阻止事件通过元素传播

[英]Javascript prevent event propagation through element

Working with google maps which has infowindows that popup. 使用带有弹出的信息窗口的Google地图。 These infowindows have images which are click-able. 这些信息窗口具有可单击的图像。 As a result I need to be able to propagate events in the infowindow. 结果,我需要能够在信息窗口中传播事件。 However I am also able to click THROUGH the infowindow to other markers which causes the current infowindow to close and it to open a new infowindow. 但是,我也可以通过信息窗口单击其他标记,这将导致当前信息窗口关闭并打开一个新的信息窗口。

I dont think this issue is specific to google maps. 我不认为此问题特定于Google地图。 Is there a way to stop events from propagating through an element? 有没有办法阻止事件通过元素传播?

Thought the below code would help but it didnt. 认为以下代码会有所帮助,但没有帮助。

$(document).on('touchstart', '.infoWindow', function(e){
  if ($(e.currentTarget) == $(this)) e.stopPropagation();
 });
 if ($(e.currentTarget) == $(this)) 

This is never true. 从来都不是真的。 It creates two distinct jQuery instances, which - even if they contain the same element - are not the same object. 它创建了两个不同的jQuery实例,即使它们包含相同的元素,它们也不是同一对象。 You might have wanted to do 你可能想做

 if (e.currentTarget == this) 

but this is always true - by definition of the event dispatch algorithm, the this value of an event listener and the currentTarget of the event object always refer to the same thing. 但这始终是正确的-根据事件分配算法的定义,事件侦听器的this值和事件对象的currentTarget始终引用同一事物。 Hell, even jQuery does this . 地狱, 甚至jQuery都这样做

So you should just write 所以你应该写

$(document).on('touchstart', '.infoWindow', function(e){
    e.stopPropagation();
});

to prevent touchstart events from bubbling through your infoWindows. 以防止touchstart事件通过infoWindows冒泡。

You cannot stop the event propagation when you use event delegation. 使用事件委派时,无法停止事件传播。 Event delegation relies on the bubbleing event, so by the time the delegated handler gets the event, the event already bubbled through every other element. 事件委托依赖于冒泡事件,因此,在委托处理程序获取事件时,该事件已经冒泡通过其他所有元素。 You need to attach your event listener directly to the element. 您需要将事件侦听器直接附加到元素。

$('.infoWindow').on('touchstart', function(e){
    e.stopPropagation();
});

Event delegation works by adding the event listener to the document , then every time the document receives that touchstart event, jQuery checks the source element and all of its parent if they match the given selector. 事件委托的工作原理是将事件侦听器添加到document ,然后每次document接收到touchstart事件时,jQuery都会检查源元素及其所有父元素(如果它们与给定的选择器匹配)。 If one matches, the handler gets invoked. 如果一个匹配,则处理程序被调用。 This is why you don't need to add the listener every time you add a new element that would match the given selector. 这就是为什么您不必在每次添加与给定选择器匹配的新元素时都添加侦听器的原因。

Setting a background color of the .infoWindow element might be a solution. 设置.infoWindow元素的背景色可能是一种解决方案。 If it should be transparent, you can use as follows: 如果应该透明,则可以使用以下方法:

background-color: rgba(255, 0, 0, 0);

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

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