确定并绑定点击或“触摸”事件

时间:2012-07-10 03:42:42

标签: javascript android jquery iphone mobile

我正在使用以下代码绑定“click”或“touchstart”事件(使用jQuery的on(eventType, function() { ... }))。

var what = (navigator.userAgent.match(/iPad/i)) ? 'touchstart' : 'click';

后来:

$foo.on(what, function() { ... });

...适用于iPad和“其他一切”,但我担心上面的代码有“iPad隧道视觉”...

我的问题:

所有其他设备(例如Android平板电脑)是否都有类似名称的“touchstart”事件?如果是这样,我如何改进上述代码,以便我可以考虑这些事件类型?

换句话说,我如何在上述代码(不仅仅是iPad)中考虑更广泛的触控设备?


编辑#1

你们有什么想法:

var foo = ('ontouchstart' in window) ? 'touchstart' : ((window.DocumentTouch && document instanceof DocumentTouch) ? 'tap' : 'click');

注意:上述大多数逻辑都是from Modernizr here

上述内容似乎适用于Firefox / iPad ......此时我没有太多可以测试的内容。

我喜欢上述内容的是我不是UA嗅闻。 :)

tap是否适用于所有其他触控设备?


编辑#2

一些interesting information here,链接到此:

Creating Fast Buttons for Mobile Web Applications

不是一个直接的答案,但是在面对多个平台和设备的点击相关事件时,提供了很多关于开发人员面临的情况的细节。


编辑#3

一些good info here

  

Android和iPhone触摸事件

     

Android和iPhone版的WebKit有一些共同的触摸事件:

touchstart - triggered when a touch is initiated. Mouse equivalent - mouseDown
touchmove - triggered when a touch moves. Mouse equivalent - mouseMove
touchend - triggered when a touch ends. Mouse equivalent - mouseUp. This one is a bit special on the iPhone - see below
touchcancel - bit of a mystery

阅读完之后,我想我会将上面的代码更改为:

var foo = (('ontouchstart' in window) || (window.DocumentTouch && document instanceof DocumentTouch)) ? 'touchstart' : 'click';

当我第一次提出问题时 - 除了iPad / iPhone之外无法访问任何其他内容 - 我认为touchstart是特定于iOS的事件;它现在看起来像touchstart,而click将涵盖触控设备的大部分(如果不是全部)基础。


2014年8月更新:

如果有任何帮助,我在这里发布了一些实用程序类:

  • mhulse / no-x.js

      

    [no-js] [no-touch]用于放入HTML模板的JavaScript实用程序,这些模板将添加jstouch类以供CSS和/或JS使用。

3 个答案:

答案 0 :(得分:13)

我强烈建议不要使用UA来确定您是否处于触控环境中。

改为使用Modernizr:http://modernizr.com/ 以下代码将识别除Windows Phone 7之外的任何内容,因为Windows Phone 7不会触发常规浏览器触摸事件。但是,WP8最有可能被正确识别。

if (Modernizr.touch){
   // bind to touchstart, touchmove, etc and watch `event.streamId`
} else {
   // bind to normal click, mousemove, etc
}

答案 1 :(得分:12)

这可能对您有用:

var clickEvent = ((document.ontouchstart!==null)?'click':'touchstart');
$("#mylink").on(clickEvent, myClickHandler);

答案 2 :(得分:9)

iOS和Android都有触摸事件,但Windows在IE中使用MSPointer事件。如果您需要跨设备解决方案,请尝试使用pointer.js或从中学习:

https://github.com/borismus/pointer.js