touchend事件属性

51

如果我使用以下代码捕获来自移动设备的所有touchend事件:

$(document.body).bind('touchend', function (e) {
var touch = e.touches[0]; // doesnt work
...

我需要从e参数中获取touch.screenX、touch.screenY、touch.clientX和touch.clientY。我看到的所有例子都建议使用e.touches来获取触摸详细信息,例如e.touches[0]。但在我的iPad测试中,e.touches始终为undefined。我没有使用任何jQuery插件。

我还尝试了e.targetTouches,但也是undefined。

有人能帮忙吗?

2个回答

104

实际上,释放的触摸事件将在changedTouches数组中找到:

e.changedTouches[0].pageX // 获取释放触摸事件的结束x页面坐标

我认为这比通过originalEvent属性稍微可靠一些。

您可以在此处阅读更多关于changedTouches的内容: http://www.w3.org/TR/touch-events/#changedtouches-of-a-touchevent


我同意,这是正确的解决方案。我自己也在使用它,因为它具有所需的正确数据,而且为什么要混合更多不必要的API呢? - Chef Pharaoh
2
如果您正在使用jQuery,那么在Android上就不是这种情况。$('#test').on('touchend', function (evt) { console.log(evt.changedTouches); });为空,如果您执行$('#test').bind('touchend'...也是一样的。但是,如果您将jQuery从方程式中剔除,并使用getElementBy和addEventListener,它就可以正常工作。 - WORMSS
@WORMSS:关于jQuery event.originalEvent属性的答案不太清楚。这个问题在这里得到了明确的解决 - http://stackoverflow.com/questions/14999724/touchstart-in-javascript-no-longer-returns-touchlist - Nolo
e.originalEvent.changedTouches[0].pageX 是正确的答案! - devpelux
1
这结束了我数周的挣扎。谢谢。 - thednp

10

touches属性是一个TouchList对象。你可以在这里查看TouchList类的参考。

如果你使用以下示例代码来监视它的长度属性,它会在#log div中显示:

$('#element').bind('touchstart', function(event) 
{
    $('#log').append(event.originalEvent.touches.length+'<br/>');
});

$('#element').bind('touchmove', function(event) 
{
    $('#log').append(event.originalEvent.touches.length+'<br/>');
});

$('#element').bind('touchend', function(event) 
{
    $('#log').append(event.originalEvent.touches.length+'<br/>');
});

当执行touchstart和touchmove时,您将获得1,而在执行touchend时获得0。这就是为什么从e.touches[0]获取undefined的原因。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接