11

我不明白如何使用 event.touches 属性。例如,要获取 iPad/iPhone 上的手指数,您应该使用

event.touches.length

那为什么这个示例代码不起作用?

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

但这是有效的:

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

不应该反过来吗?

4

1 回答 1

18

在第二种情况下,您将依赖浏览器的全局(和原始)event对象,而不是特定于 jQuery 的对象(在支持 global 的浏览器上event,并非所有人都支持 - 例如,Firefox 不支持 - 因为它是 Microsoft只有其他人复制的东西)。

听起来 jQuery 没有touches在其自定义事件对象中传递该属性。如事件对象的文档中所述,您可以event.originalEvent在第一个示例中使用它来访问它具有的“特殊属性”,同时仍然可以获得 jQuery 规范化事件对象的好处,例如:

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

...或者您可以通过在脚本开头执行此操作来告诉 jQuery 复制该属性:

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

...因此您的第一个示例应该开始工作。


旁注:如果你没有使用jQuery Touch,你可以看看它。我的猜测是,除了它所做的其他事情之外,它还添加了touches如上所示的属性(但这只是一个猜测)。

于 2011-11-01T11:13:23.740 回答