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

这可能吗?


当前回答

您可以使用以下代码:

function isTouchDevice() {
   var el = document.createElement('div');
   el.setAttribute('ongesturestart', 'return;'); // or try "ontouchstart"
   return typeof el.ongesturestart === "function";
}

来源:detection touch-based browsing and @mplungjan post。

上述解决方案是基于检测事件的支持,没有浏览器嗅探文章。

您可以在下面的测试页面检查结果。

请注意,上面的代码只测试浏览器是否支持触摸,而不是设备本身。所以如果你的笔记本电脑有触摸屏,你的浏览器可能不支持触摸事件。最新的Chrome浏览器支持触摸事件,但其他浏览器可能不支持。

你也可以试试:

if (document.documentElement.ontouchmove) {
  // ...
}

但它可能不适用于iPhone设备。

其他回答

我喜欢这个:

function isTouchDevice(){
    return window.ontouchstart !== undefined;
}

alert(isTouchDevice());

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

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)

由于引入了交互媒体功能,你可以简单地做到:

if(window.matchMedia("(pointer: coarse)").matches) {
    // touchscreen
}

https://www.w3.org/TR/mediaqueries-4/#descdef-media-any-pointer

更新(由于评论):上面的解决方案是检测“粗指针”——通常是触摸屏——是否是主要输入设备。如果你想检测一个带有鼠标的设备是否也有触摸屏,你可以使用任意指针:粗。

有关更多信息,请查看这里:检测浏览器没有鼠标,只能触摸

如果您使用Modernizr,使用Modernizr是非常容易的。如前所述,触摸。

但是,我更喜欢使用Modernizr的组合。触摸和用户代理测试,只是为了安全。

var deviceAgent = navigator.userAgent.toLowerCase();

var isTouchDevice = Modernizr.touch || 
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/)  || 
deviceAgent.match(/(iemobile)/) || 
deviceAgent.match(/iphone/i) || 
deviceAgent.match(/ipad/i) || 
deviceAgent.match(/ipod/i) || 
deviceAgent.match(/blackberry/i) || 
deviceAgent.match(/bada/i));

if (isTouchDevice) {
        //Do something touchy
    } else {
        //Can't touch this
    }

如果不使用Modernizr,可以简单地替换Modernizr。在document.documentElement中使用('ontouchstart')

还要注意,测试用户代理iemobile将为您提供比Windows Phone更广泛的检测到的微软移动设备。

也可以看到这个SO问题

工作小提琴

我是这样做到的;

function isTouchDevice(){
    return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}

if(isTouchDevice()===true) {
    alert('Touch Device'); //your logic for touch device
}
else {
    alert('Not a Touch Device'); //your logic for non touch device
}