我如何检测JavaScript中的设备触摸支持? [英] How can I detect device touch support in JavaScript?

查看:127
本文介绍了我如何检测JavaScript中的设备触摸支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去,当检测设备是否支持JavaScript中的触摸事件时,我们可以这样做:

  var touch_capable =(document.documentElement中的'ontouchstart'); 

然而,Google Chrome(17.x.x +)会返回 true 进行上述检查,即使底层设备不支持触摸事件。例如,在Windows 7上运行上面的代码会返回true,因此如果我们将它与以下类似的代码结合:

  var start_evt = (touch_capable)? 'ontouchstart':'onmousedown'; 

在谷歌浏览器中,事件永远不会被触发,因为我们绑定到 ontouchstart 。总之,有没有人知道一个可靠的方法来规避这一点?我正在执行以下检查:

  var touch_capable =(document.documentElement&&& navigator.userAgent中的'ontouchstart' .toLowerCase()。indexOf('chrome')== -1)

这远非理想...

解决方案

正确答案是处理两个事件类型 - 它们不相互。

为了获得更可靠的触摸支持测试,还可以查找 window.DocumentTouch&&文档instanceof DocumentTouch 这是 Modernizr



更好的是,您可以自己使用Modernizr并让它为您做功能检测。



请注意,虽然您无法防止误报,因此我的第一行是 - 您已经 来支持这两种行为。


In the past, when detecting whether a device supports touch events in JavaScript, we could do something like this:

var touch_capable = ('ontouchstart' in document.documentElement);

However, Google Chrome (17.x.x+) returns true for the above check, even if the underlying device does not support touch events. For example, running the above code on Windows 7 returns true, and thus if we combine it with something like:

var start_evt = (touch_capable) ? 'ontouchstart' : 'onmousedown';

On Google Chrome, the event is never fired since we're binding to ontouchstart. In short, does anyone know a reliable way to circumvent this? I am currently running the following check:

var touch_capable = ('ontouchstart' in document.documentElement && navigator.userAgent.toLowerCase().indexOf('chrome') == -1)

Which is far from ideal...

解决方案

The correct answer is to handle both event types - they're not mutually exclusive.

For a more reliable test for touch support, also look for window.DocumentTouch && document instanceof DocumentTouch which is one of the tests used by Modernizr

Better yet, just use Modernizr yourself and have it do the feature detection for you.

Note though that you cannot prevent false positives, hence my first line above - you've got to support both.

这篇关于我如何检测JavaScript中的设备触摸支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆