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

这可能吗?


当前回答

当连接鼠标时,可以假设有相当高的点击率(我想说几乎100%),用户在页面准备好后移动鼠标至少一小段距离-没有任何点击。下面的机制检测到这一点。如果检测到,我认为这是缺少触摸支持的标志,或者,如果支持,在使用鼠标时不太重要。如果未检测到触摸设备,则假定为触摸设备。

这种方法可能不适合所有目的。它可以用来控制基于加载页面上的用户交互激活的功能,例如图像查看器。下面的代码还将把mouemove事件绑定在没有鼠标的设备上,因为它现在很突出。其他方法可能更好。

大致是这样的(对jQuery来说很抱歉,但在纯Javascript中类似):

var mousedown, first, second = false;
var ticks = 10;
$(document).on('mousemove', (function(e) {
    if(UI.mousechecked) return;
    if(!first) {
        first = e.pageX;
        return;
        }
    if(!second && ticks-- === 0) {
        second = e.pageX;
        $(document).off('mousemove'); // or bind it to somewhat else
        }
    if(first  && second  && first !== second && !mousedown){
        // set whatever flags you want
        UI.hasmouse = true;
        UI.touch = false;
        UI.mousechecked = true;
    }

    return;
}));
$(document).one('mousedown', (function(e) {
    mousedown = true;
    return;
}));
$(document).one('mouseup', (function(e) {
    mousedown = false;
    return;
}));

其他回答

虽然它只是alpha版本,但jquery移动框架值得一试。它将在移动浏览器中规范化这些类型的事件。也许可以看看他们在做什么。我假设jquery-mobile.js与这个框架有所不同。

这种方法对我来说很有效,它等待第一次用户交互,以确保他们是在触摸设备上

var touchEnabled = false;
$(document.body).one('touchstart',
    function(e){
        touchEnabled=true;
        $(document.documentElement).addClass("touch");
        // other touch related init 
        //
    }
);

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

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

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

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

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

这个即使在Windows Surface平板电脑上也能很好地工作!!

function detectTouchSupport {
msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture,
touchSupport = (( "ontouchstart" in window ) || msGesture || window.DocumentTouch &&     document instanceof DocumentTouch);
if(touchSupport) {
    $("html").addClass("ci_touch");
}
else {
    $("html").addClass("ci_no_touch");
}
}

我使用:

if(jQuery.support.touch){
    alert('Touch enabled');
}

jQuery mobile 1.0.1