0

我试图弄清楚用户代理是否是触摸设备,如果是我想加载 addEventListener ...

if( (navigator.userAgent.match(/iPhone/i)) || 
    (navigator.userAgent.match(/iPad/i)) {
    document.addEventListener("touchstart", function() {},false);
}) 

另外,我如何检测 Android 设备和可能的其他触摸设备?

4

2 回答 2

0

http://modernizr.github.com/Modernizr/touch.html

这就是浏览器功能库modernizr 的做法。为什么不使用它们?

于 2012-05-18T03:06:07.020 回答
0

我前段时间用来测试触摸事件的一个简单脚本是:

var hasTouch = (function(){
  if (document && document.createEvent) {
    try {
      document.createEvent('GestureEvent');
      document.createEvent('TouchEvent');
      return true;
    } catch (e) {
      return false;
    }
  }
})(); 

我已经有一段时间没有使用它了,所以可能有更好的方法,但上述方法仍然有效。

您还可以尝试 Kangax 的文章Detecting event support without browser sniffing,可能类似于:

  function isTouchEventSupported(eventName) {
    var el = document.createElement('div');
    eventName = 'on' + eventName;
    var isSupported = (eventName in el);

    if (!isSupported) {
      el.setAttribute(eventName, 'return;');
      isSupported = typeof el[eventName] == 'function';
    }
    el = null;
    return isSupported;
  }

  alert(isTouchEventSupported('touchstart'));  // false in IE 8
于 2012-05-18T02:54:07.260 回答