最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS: How does event.touches property work? - Stack Overflow

programmeradmin2浏览0评论

I don't understand how to use the event.touches property. For example to get the number of fingers on a iPad/iPhone you should use

event.touches.length

Then why is this example code not working?

$('.image').bind('touchstart', function(event) {
  alert(event.touches.length);
});

But this is working:

$('.image').bind('touchstart', function() {
  alert(event.touches.length);
});

Shouldn't it be the other way round?

I don't understand how to use the event.touches property. For example to get the number of fingers on a iPad/iPhone you should use

event.touches.length

Then why is this example code not working?

$('.image').bind('touchstart', function(event) {
  alert(event.touches.length);
});

But this is working:

$('.image').bind('touchstart', function() {
  alert(event.touches.length);
});

Shouldn't it be the other way round?

Share Improve this question asked Nov 1, 2011 at 11:06 TinaTina 4912 gold badges5 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 18

In the second case, you're falling back on the browser's global (and raw) event object rather than the jQuery-specific one (on browsers that support a global event, not all do — Firefox doesn't, for instance — because it's a Microsoft thing only some others have copied).

It sounds like jQuery isn't passing the touches property on in its custom event object. As described in the event object's documentation, you can use event.originalEvent in your first example to access the "special properties" it has while still getting the benefits of the jQuery normalized event object, e.g.:

$('.image').bind('touchstart', function(event) {
  alert(event.originalEvent.touches.length);
});

...or you can tell jQuery to copy that property over by doing this once at the beginning of your script:

jQuery.event.props.push("touches");

...whereupon your first example should start working.


Side note: If you're not using jQuery Touch, you might look at it. My guess is that in addition to the other things it does, it adds the touches property as shown above (but that's just a guess).

发布评论

评论列表(0)

  1. 暂无评论