2011-08-25 106 views
44

如果我赶上从移动设备与所有touchend事件:touchend事件属性

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

我需要从电子放慢参数得到touch.screenX,touch.screenY,touch.clientX和touch.clientX。我见过的所有例子都表明e.touches将会是一个集合,你可以通过e.touches[0]获得触摸细节。在我对ipad的测试中,e.touches始终未定义。我没有使用任何jQuery插件。

也试过e.targetTouches,这也是未定义的。

任何人都可以帮忙吗?

回答

96

其实,发布触摸将changedTouches阵列中找到,即:

e.changedTouches[0].pageX // get the end x page coordinate for a released touch

我觉得这是略多于通过originalEvent属性会更可靠。

你可以阅读更多的changedTouches这里: http://www.w3.org/TR/touch-events/#changedtouches-of-a-touchevent

+4

不应该这是公认的答案?投票! –

+0

我同意,这是正确的解决方案。我自己正在使用它,因为它具有所需的正确数据,并且为什么要混合比需要更多的API。 –

+2

如果您使用的是jQuery,则android不是这种情况。 $('#test')。on('touchend',function(evt){console.log(evt.changedTouches);});是空的,如果你做$('#test')。bind('touchend'...,但是如果你将jquery从等式中删除并且执行getElementBy和addEventListener,它会起作用。 – WORMSS

10

touches属性是一个TouchList对象。你可以看到TouchList类参考here

如果监视与#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,执行touchEnd当一个0你将得到1。这就是为什么你从e.touches[0]获得未定义的原因。