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

这可能吗?


当前回答

关于如何在Javascript中检测页面是否显示在触摸屏设备上,我也遇到了很多困难。 在我看来,到目前为止,还没有真正的选项可以正确地检测这个选项。 浏览器要么报告桌面机器上的触摸事件(因为操作系统可能已经准备好触摸了),要么某些解决方案不能在所有移动设备上工作。

最后,我意识到我从一开始就采取了错误的方法: 如果我的页面在触摸和非触摸设备上看起来相似,我可能根本不需要担心检测属性: 我的方案是禁用触摸设备上的按钮上的工具提示,因为它们会导致双击,而我希望通过一次点击来激活按钮。

我的解决方案是重构视图,这样按钮上就不需要工具提示了,最后我也不需要用Javascript的方法来检测触摸设备了,因为这些方法都有自己的缺点。

其他回答

我喜欢这个:

function isTouchDevice(){
    return window.ontouchstart !== undefined;
}

alert(isTouchDevice());

看看这篇文章,它给出了一个非常好的代码片段,告诉你当检测到触摸设备时该怎么做,或者如果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();
}

不,不可能。给出的优秀答案永远都是片面的,因为任何给定的方法都会产生假阳性和假阴性。由于操作系统api的原因,甚至浏览器也不总是知道是否存在触摸屏,而且在浏览器会话期间,这一事实可能会发生变化,特别是使用kvm类型的安排。

详见这篇优秀的文章:

http://www.stucox.com/blog/you-cant-detect-a-touchscreen/

这篇文章建议你重新考虑那些让你想要检测触摸屏的假设,它们可能是错误的。(我检查了我自己的应用程序,我的假设确实是错误的!)

文章总结道:

对于布局,假设每个人都有触摸屏。鼠标用户可以使用 大型UI控件比触摸用户使用小控件容易得多 的人。悬浮状态也是如此。 对于事件和交互,假设任何人都有触摸屏。 实现键盘、鼠标和触摸交互, 确保互不妨碍。

使用上面所有的注释,我已经组装了下面的代码,是为我的需要工作:

var isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));

我在iPad、Android(浏览器和Chrome)、黑莓Playbook、iPhone 4s、Windows Phone 8、IE 10、IE 8、IE 10(带触摸屏的Windows 8)、Opera、Chrome和Firefox上进行了测试。

它目前在Windows Phone 7上无法运行,我还没有找到针对该浏览器的解决方案。

希望有人觉得这有用。

这个即使在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");
}
}