我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。

这可能吗?


当前回答

我认为最好的方法是:

var isTouchDevice =
    (('ontouchstart' in window) ||
    (navigator.maxTouchPoints > 0) ||
    (navigator.msMaxTouchPoints > 0));
if(!isTouchDevice){
    /* Code for touch device /*
}else{
    /* Code for non touch device */
}

其他回答

实际的答案似乎是一个考虑上下文的答案:

1)公共站点(无法登录) 编写UI代码以同时使用这两个选项。

2)登录站点 捕获登录表单上是否发生了鼠标移动,并将其保存到隐藏的输入中。该值与登录凭据一起传递,并添加到用户的会话中,因此可以在会话期间使用它。

Jquery只添加到登录页面:

$('#istouch').val(1); // <-- value will be submitted with login form

if (window.addEventListener) {
    window.addEventListener('mousemove', function mouseMoveListener(){
        // Update hidden input value to false, and stop listening
        $('#istouch').val(0); 
        window.removeEventListener('mousemove', mouseMoveListener);
    });
} 

(@Dave Burt +1, @Martin Lantzsch +1)

这个问题

由于混合设备使用触摸和鼠标输入的组合,你需要能够动态地改变状态/变量,控制一段代码是否应该运行,如果用户是触摸用户或不是。

触控设备也可以在点击时触发鼠标移动。

解决方案

Assume touch is false on load. Wait until a touchstart event is fired, then set it to true. If touchstart was fired, add a mousemove handler. If the time between two mousemove events firing was less than 20ms, assume they are using a mouse as input. Remove the event as it's no longer needed and mousemove is an expensive event for mouse devices. As soon as touchstart is fired again (user went back to using touch), the variable is set back to true. And repeat the process so it's determined in a dynamic fashion. If by some miracle mousemove gets fired twice on touch absurdly quickly (in my testing it's virtually impossible to do it within 20ms), the next touchstart will set it back to true.

在Safari iOS和Chrome for Android上进行了测试。

注意:不是100%确定的指针事件为MS Surface等。

Codepen演示


const supportsTouch = 'ontouchstart' in window;
let isUsingTouch = false;

// `touchstart`, `pointerdown`
const touchHandler = () => {
  isUsingTouch = true;
  document.addEventListener('mousemove', mousemoveHandler);
};

// use a simple closure to store previous time as internal state
const mousemoveHandler = (() => {
  let time;
  
  return () => {
    const now = performance.now();

    if (now - time < 20) {
      isUsingTouch = false;
      document.removeEventListener('mousemove', mousemoveHandler);
    }

    time = now;
  }
})();

// add listeners
if (supportsTouch) {
  document.addEventListener('touchstart', touchHandler);
} else if (navigator.maxTouchPoints || navigator.msMaxTouchPoints) {
  document.addEventListener('pointerdown', touchHandler);
}

jQuery扩展支持对象:

jQuery.support.touch = 'ontouchend' in document;

现在你可以在任何地方检查它,像这样:

if( jQuery.support.touch )
   // do touch stuff

不,不可能。给出的优秀答案永远都是片面的,因为任何给定的方法都会产生假阳性和假阴性。由于操作系统api的原因,甚至浏览器也不总是知道是否存在触摸屏,而且在浏览器会话期间,这一事实可能会发生变化,特别是使用kvm类型的安排。

详见这篇优秀的文章:

http://www.stucox.com/blog/you-cant-detect-a-touchscreen/

这篇文章建议你重新考虑那些让你想要检测触摸屏的假设,它们可能是错误的。(我检查了我自己的应用程序,我的假设确实是错误的!)

文章总结道:

对于布局,假设每个人都有触摸屏。鼠标用户可以使用 大型UI控件比触摸用户使用小控件容易得多 的人。悬浮状态也是如此。 对于事件和交互,假设任何人都有触摸屏。 实现键盘、鼠标和触摸交互, 确保互不妨碍。

你可以安装modernizer并使用一个简单的触摸事件。这是非常有效的,工作在每一个设备上,我已经测试了它包括窗户表面!

我已经创建了一个jsFiddle

function isTouchDevice(){
    if(Modernizr.hasEvent('touchstart') || navigator.userAgent.search(/Touch/i) != -1){
         alert("is touch");
            return true;
         }else{
            alert("is not touch");
            return false;
    }
}