用于触摸设备的Eventlistener

时间:2012-05-18 00:02:37

标签: javascript mobile user-agent

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

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

此外,我如何检测Android设备以及可能的其他触控设备?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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

相关问题