Javascript,检测触摸设备

时间:2013-03-05 10:39:59

标签: javascript touch

我正在使用此功能来检测设备是否为触控设备:

function is_touch_device()
{
    return !!('ontouchstart' in window) || !!('onmsgesturechange' in window);
};

从这里获得此功能:What's the best way to detect a 'touch screen' device using JavaScript?

但是自Chrome 25(25.0.1364)以来,它在我的桌面上返回true,而不是触控设备。 我还将IE9更新为IE10,它在IE中返回true!

搜索周围但找不到任何有用的解决方法,除非使用类似的内容:http://detectmobilebrowsers.com/

你推荐什么?

我期待你的回复!

5 个答案:

答案 0 :(得分:4)

代码工作正常,浏览器能够理解触摸事件,只是因为您的屏幕不可触摸并不意味着浏览器不支持该功能。您要测试的是硬件功能,这是不可测试的。您可以使用不同的方式,但是在触摸一次之后查看用户是否实际使用触摸界面,例如this文章描述,或者大型图书馆使用的许多其他内容,例如Modernizer。

作为参考,上面文章中实际使用的代码是:

function isTouchDevice() {
   var el = document.createElement('div');
   el.setAttribute('ongesturestart', 'return;');
   if(typeof el.ongesturestart == "function"){
      return true;
   }else {
      return false
   }
}

答案 1 :(得分:3)

这似乎有效:

function isTouchEnabled() { return !!document.createTouch; }

答案 2 :(得分:3)

您可以使用Modernizr来检测触控功能。

这个问题与What's the best way to detect a 'touch screen' device using JavaScript?非常相似,也许应该被视为重复。

答案 3 :(得分:2)

当我访问我从笔记本电脑上工作过的网站时,我也遇到了误报IE10触摸问题。最初的is_touch_device方法,我使用了基本相同的东西。我修改了该语句的后半部分如下:

function is_touch_device()
{
    return !!('ontouchstart' in window) || (!!('onmsgesturechange' in window) && !!window.navigator.maxTouchPoints);
}
基于这篇文章,

window.navigator.maxTouchPoints似乎是IE10中的特定内容:http://msdn.microsoft.com/en-us/library/hh772144(v=vs.85).aspx

答案 4 :(得分:0)

您可以在服务器上使用51dergees.mobi进行适当更改页面视图的检测。它具有HasTouchScreen,IsSmartPhone,IsTablet属性等。