如何使用JavaScript最佳地检测“触屏”设备?

525

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

这种可能性存在吗?


这是更好的方法 var x = 'touchstart' in document.documentElement; console.log(x) // 如果支持,则返回true // 否则返回false - Risa__B
为什么即使有新技术出现,这个线程还是被保护了呢? - Andy Hoffman
38个回答

0

目前来看,这似乎对我很好用:

//Checks if a touch screen
is_touch_screen = 'ontouchstart' in document.documentElement;

if (is_touch_screen) {
  // Do something if a touch screen
}
else {
  // Not a touch screen (i.e. desktop)
}

0
你可以使用以下代码:
function isTouchDevice() {
   var el = document.createElement('div');
   el.setAttribute('ongesturestart', 'return;'); // or try "ontouchstart"
   return typeof el.ongesturestart === "function";
}

来源:检测基于触摸的浏览@mplungjan帖子

上述解决方案基于无需浏览器嗅探即可检测事件支持文章。

您可以在以下测试页面中查看结果。

请注意,上述代码仅测试浏览器是否支持触摸,而不是设备。因此,如果您使用带有触摸屏的笔记本电脑,则您的浏览器可能不支持触摸事件。最近的Chrome支持触摸事件,但其他浏览器可能不支持。

您也可以尝试:

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

但在 iPhone 设备上可能无法正常工作。


0

扩展jQuery support 对象:

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

现在你可以在任何地方检查它,就像这样:
if( jQuery.support.touch )
   // do touch stuff

0
我知道已经过了很多年,但我找到了一个相关的解决方案: 如何绑定'touchstart'和'click'事件,但不对两者都响应? 这个jQuery函数监听触摸和鼠标事件。无论哪个事件先触发,都会禁用第二个事件。以下是我如何使用它来使一个div只响应其中一个事件的方法:
$(".phoneBtn").on( "mousedown touchstart", function(event) {
                      if (event.type == "touchstart") {
                          pressButton(this);
                          $(this).off('mousedown');
                          //Only touchstart event is heard

                      } else if (event.type == "mousedown") {
                          $(this).off('touchstart');
                          pressButton(this);
                          //Only mousedown event is heard
                      } 
                  )}

-2
$.support.touch ? "true" : "false";

-2

如果你测试document.documentElement是否支持touchstart,那么这很简单。

var x = 'touchstart' in document.documentElement;
console.log(x)
// return true if is supported
// else return false


-3

尽管它只处于alpha阶段,但jquery移动框架值得一试。它将在移动浏览器中规范这些类型的事件。也许可以看看他们正在做什么。我假设jquery-mobile.js与此框架不同。


jQuery Mobile非常棒,我们用它来进行移动开发,但我想要能够专门测试触摸屏设备。似乎只使用jQuery Mobile无法实现这一点。 - screenm0nkey
对,它不是那样工作的。它使用渐进增强。 - ScottE

-4

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接