我编写了一个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设备。

其他回答

var isTouchScreen = 'createTouch' in document;

or

var isTouchScreen = 'createTouch' in document || screen.width <= 699 || 
    ua.match(/(iPhone|iPod|iPad)/) || ua.match(/BlackBerry/) || 
    ua.match(/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());

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

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();