我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
当前回答
您可以使用以下代码:
function isTouchDevice() {
var el = document.createElement('div');
el.setAttribute('ongesturestart', 'return;'); // or try "ontouchstart"
return typeof el.ongesturestart === "function";
}
来源:detection touch-based browsing and @mplungjan post。
上述解决方案是基于检测事件的支持,没有浏览器嗅探文章。
您可以在下面的测试页面检查结果。
请注意,上面的代码只测试浏览器是否支持触摸,而不是设备本身。所以如果你的笔记本电脑有触摸屏,你的浏览器可能不支持触摸事件。最新的Chrome浏览器支持触摸事件,但其他浏览器可能不支持。
你也可以试试:
if (document.documentElement.ontouchmove) {
// ...
}
但它可能不适用于iPhone设备。
其他回答
这种方法对我来说很有效,它等待第一次用户交互,以确保他们是在触摸设备上
var touchEnabled = false;
$(document.body).one('touchstart',
function(e){
touchEnabled=true;
$(document.documentElement).addClass("touch");
// other touch related init
//
}
);
如果您使用Modernizr,使用Modernizr是非常容易的。如前所述,触摸。
但是,我更喜欢使用Modernizr的组合。触摸和用户代理测试,只是为了安全。
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,可以简单地替换Modernizr。在document.documentElement中使用('ontouchstart')
还要注意,测试用户代理iemobile将为您提供比Windows Phone更广泛的检测到的微软移动设备。
也可以看到这个SO问题
如果你测试document.documentElement中支持touchstart,这就很简单了
var x = 'touchstart'在document.documentElement; console.log (x) //如果支持返回true //否则返回false
工作小提琴
我是这样做到的;
function isTouchDevice(){
return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}
if(isTouchDevice()===true) {
alert('Touch Device'); //your logic for touch device
}
else {
alert('Not a Touch Device'); //your logic for non touch device
}
使用上面所有的注释,我已经组装了下面的代码,是为我的需要工作:
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上无法运行,我还没有找到针对该浏览器的解决方案。
希望有人觉得这有用。