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

这可能吗?


当前回答

有一种方法比检查他们是否拥有触摸屏更好,那就是检查他们是否正在使用触摸屏,而且这更容易检查。

if (window.addEventListener) {
    var once = false;
    window.addEventListener('touchstart', function(){
        if (!once) {
            once = true;
            // Do what you need for touch-screens only
        }
    });
}

其他回答

更新:在将整个功能检测库拉入你的项目之前,请阅读下面blmstr的回答。检测实际的触摸支持更加复杂,Modernizr只涵盖了一个基本的用例。

Modernizr是一种很棒的轻量级方法,可以在任何网站上进行各种特征检测。

它只是为每个特性在html元素中添加类。

然后你可以在CSS和JS中轻松地瞄准这些功能。例如:

html.touch div {
    width: 480px;
}

html.no-touch div {
    width: auto;
}

和Javascript (jQuery示例):

$('html.touch #popup').hide();

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

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

更新2021

要查看以前的答案,请查看历史记录。我决定从头开始,因为在保存历史的时候,它变得难以控制。

我最初的回答是,使用与Modernizr使用的相同功能可能是一个好主意,但这不再有效,因为他们删除了这个PR: https://github.com/Modernizr/Modernizr/pull/2432上的“touchevents”测试,因为这是一个令人困惑的主题。

话虽如此,这应该是一个相当好的检测浏览器是否具有“触摸功能”的方法:

function isTouchDevice() {
  return (('ontouchstart' in window) ||
     (navigator.maxTouchPoints > 0) ||
     (navigator.msMaxTouchPoints > 0));
}

但是对于比我更聪明的人写过的更高级的用例,我建议阅读这些文章:

斯图·考克斯:你无法检测触摸屏 触摸检测:它是“为什么”,而不是“如何” Patrick H. Lauke的敏感演讲

您可以使用以下代码:

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设备。

看看这篇文章,它给出了一个非常好的代码片段,告诉你当检测到触摸设备时该怎么做,或者如果touchstart事件被调用了该怎么做:

$(function(){
  if(window.Touch) {
    touch_detect.auto_detected();
  } else {
    document.ontouchstart = touch_detect.surface;
  }
}); // End loaded jQuery
var touch_detect = {
  auto_detected: function(event){
    /* add everything you want to do onLoad here (eg. activating hover controls) */
    alert('this was auto detected');
    activateTouchArea();
  },
  surface: function(event){
    /* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
    alert('this was detected by touching');
    activateTouchArea();
  }
}; // touch_detect
function activateTouchArea(){
  /* make sure our screen doesn't scroll when we move the "touchable area" */
  var element = document.getElementById('element_id');
  element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
  /* modularize preventing the default behavior so we can use it again */
  event.preventDefault();
}