stopPropagation()与tap事件 [英] stopPropagation() with tap event

查看:156
本文介绍了stopPropagation()与tap事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 hammer.js ,似乎我 event.stopPropagation()不适用于点击事件。

I'm using hammer.js and it appears that I event.stopPropagation() doesn't work with tap event.

如果我点击孩子,相关事件会被触发但是父亲的事件也被触发,我不希望这样。

If I click on the child, the associated event is triggered but parent's event is also triggered and I don't want that.

$('#parent').hammer().bind('tap', function(e) {
    $(this).css('background', 'red');
});​​​​​​​​

$('#child').hammer().bind('tap', function(e) {
    e.stopPropagation();
    $(this).css('background', 'blue');
});

这是一个例子: http://jsfiddle.net/Mt9gV/


我也试过 jGestures 和问题似乎是一样的。
如何使用其中一个库实现此结果? (如果需要的话,还是另一个)

​ I also tried with jGestures and the issue seems to be the same. How can I achieve this result with one of those library? (or another one if it is needed)

推荐答案

正如另一条评论中提到的,正如你所做的那样,人们可以期待 event.stopPropagation()将是阻止事件冒泡到父母所需的全部内容。

As mentioned in another comment, one would expect, as you did, that calling event.stopPropagation() would be all that is require to stop the event from bubbling up to the parent.

详细信息但是,在Hammer.js 中,情况并非如此。 Hammer为您调用 $(el).hammer()的每个元素创建一个新的手势状态机。因此,当浏览器触发子项触摸事件时,它首先由子逻辑处理,然后由父项逻辑处理。因此,要阻止父级获取点击事件,您必须阻止父级的锤子状态机获取原始触摸事件。通常,调用 event.stopPropagation()也将停止原始事件的传播。但是,hammer.js的点击事件是在 touchend 上触发的,但是 originalEvent 是缓存的 touchstart 事件。因此,停止传播原始事件没有任何效果,因为 touchstart 事件早已在DOM中冒出来。

Details: However, in Hammer.js this is not so. Hammer creates a new gesture state machine for each element on which you call $(el).hammer(). So when a touch event is fired on the child by the browser it is processed first by the logic for child and then again by the logic on the parent. As such to stop the parent from getting the tap event you must prevent the parent's hammer state machine from getting the original touch event. Generally, calling event.stopPropagation() will also stop the propagation of the original event. However, hammer.js's tap event is fired on touchend but the originalEvent is the cached touchstart event. As such, stopping propagation on the original event has no effect because the touchstart event has long ago bubbled up through the DOM.

解决方案?我认为这是锤子中的错误 - 提交修正 originalEvent 的拉取请求点击事件。正如其他人建议您可以检查事件的目标,但这始终是父元素 - 在我看来是另一个错误。因此,请检查 event.originalEvent.target 。这是一个 JS小提琴,实现了这个平庸的解决方案: http: //jsfiddle.net/HHRHR/

Solution? I believe this is a bug in hammer - submit a pull request that corrects the originalEvent in the tap event. As others have suggested you could check the event's target, but that's always the parent element - another bug in my opinion. So instead check the event.originalEvent.target. Here's a JS fiddle with this mediocre solution implemented: http://jsfiddle.net/HHRHR/

这篇关于stopPropagation()与tap事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆