问题
I ran into a very strange problem. I am binding the touchstart
event to an element, and would like to retrieve the X and Y co-ordinates of the event. All documentation online indicates that this is available through one of the following:
e.touches
e.targetTouches
e.changedTouches
However, the following code, called on #test
returns undefined
for all three supposed arrays when running this from jQuery:
$('#test').bind('touchstart', function(e) {
alert(e.targetTouches);
alert(e.touches);
alert(e.changedTouches);
});
You can see a demo here > http://jsfiddle.net/c7UKV/1/ (you need to view it on a mobile device, or you can go straight to the results here > http://jsfiddle.net/c7UKV/1/embedded/result/).
My question is does anyone know of a work around, or is jQuery normalizing the event in some way that I'm not aware of? The issue exists across all versions of jQuery I tested (1.6+) and also on the iOS Simulator and on physical iDevices.
As an update to the above, calling this using vanilla JavaScript (rather than jQuery) returns the correct result. For example the following code works without a problem:
document.getElementById('test').addEventListener('touchstart', checkCoords, false);
function checkCoords(e)
{
alert(e.targetTouches);
alert(e.touches);
alert(e.changedTouches);
}
So it would appear that this is a jQuery issue, rather than anything else. You can see the above working correctly in this jsFiddle.
回答1:
As described in the documentation, not every property of the original event
is copied to jQuery's normalized event object.
You can still access it using originalEvent object:
$('#test').bind('touchstart', checkCoords );
function checkCoords(e){
alert(e.originalEvent.targetTouches);
alert(e.originalEvent.touches);
alert(e.originalEvent.changedTouches);
}
来源:https://stackoverflow.com/questions/14999724/touchstart-in-javascript-no-longer-returns-touchlist