有没有一种好的、简洁的方法或技巧来判断用户是否在触摸设备上?
我知道有像这样的东西:
var isiPad = navigator.userAgent.match(/iPad/i) != null;
但我只是想知道有没有一种通用的方法来确定用户是否在触摸设备上? 因为现在市面上存在许多不仅仅是iPad的触摸设备和平板电脑。
谢谢。
有没有一种好的、简洁的方法或技巧来判断用户是否在触摸设备上?
我知道有像这样的东西:
var isiPad = navigator.userAgent.match(/iPad/i) != null;
但我只是想知道有没有一种通用的方法来确定用户是否在触摸设备上? 因为现在市面上存在许多不仅仅是iPad的触摸设备和平板电脑。
谢谢。
function isTouchDevice() {
var el = document.createElement('div');
el.setAttribute('ongesturestart', 'return;'); // or try "ontouchstart"
return typeof el.ongesturestart === "function";
}
来源:检测基于触摸的浏览。
请注意,上面的代码仅测试浏览器是否支持触摸,而不是设备。
相关链接:
在 jQuery Mobile 和 jTouch 中可能会有检测。
引入Modernizer,它是一个小型的特性检测库。之后您可以使用以下类似的代码。
if (Modernizr.touch){
// bind to touchstart, touchmove, etc and watch `event.streamId`
} else {
// bind to normal click, mousemove, etc
}
if ("ontouchstart" in document.documentElement)
{
alert("It's a touch screen device.");
}
else
{
alert("Others devices");
}
在浏览了很多地方之后,我发现这是最简单的代码
document.createEvent("TouchEvent")
不能在桌面设备上使用。所以,您可以在 if 语句中使用它。
请注意,此方法可能会在非触摸设备上产生错误。我建议检查 document.documentElement
中的 ontouchstart
。
看看这篇文章,它提供了一个非常好的代码片段,用于检测触摸设备或在调用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();
}
Modernizr.touch
非常容易。Modernizr.touch
和用户代理测试的组合,以确保安全。var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
if (isTouchDevice) {
//Do something touchy
} else {
//Can't touch this
}
Modernizr.touch
函数简单替换为('ontouchstart' in document.documentElement)
另外,请注意测试用户代理iemobile
将为您提供比Windows Phone
更广泛的检测到的Microsoft移动设备范围。
此外,还可以参考这个SO问题
/Mobile/i
正则表达式来代替那个冗长的 OR。 - Mister Smith
alert(typeof el.ongesturestart)
或者你尝试了什么?使用的是什么设备?什么操作系统?没有提供建设性意见的贬低并不能帮助任何人。而且这是两年前的帖子了。世界已经发生了变化。 - mplungjan