JS:event.touches 属性如何工作?
我不明白如何使用 event.touches 属性。例如,要获取 iPad/iPhone 上的手指数量,您应该使用
event.touches.length
那么为什么此示例代码不起作用?
$('.image').bind('touchstart', function(event) {
alert(event.touches.length);
});
但这是有效的:
$('.image').bind('touchstart', function() {
alert(event.touches.length);
});
难道不应该反过来吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在第二种情况下,您将依赖于浏览器的全局(和原始)
event
对象,而不是特定于 jQuery 的对象(在支持全局event
的浏览器上,并非所有人都这样做——例如 Firefox 就没有——因为它是微软的东西,只有其他一些人复制了)。听起来 jQuery 没有在其自定义事件对象中传递
touches
属性。如事件对象的文档中所述,您可以使用event.originalEvent
在您的第一个示例中,访问它所具有的“特殊属性”,同时仍然获得 jQuery 规范化事件对象的好处,例如:...或者您可以告诉 jQuery 通过在脚本开头执行此操作一次来复制该属性:
...您的第一个示例应该开始工作。
旁注:如果您没有使用 jQuery Touch,您可以查看它。我的猜测是,除了它所做的其他事情之外,它还添加了
touches
属性,如上所示(但这只是一个猜测)。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 globalevent
, 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 useevent.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.:...or you can tell jQuery to copy that property over by doing this once at the beginning of your script:
...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).