我编写了一个适用于桌面和移动设备的jQuery插件。我想知道是否有一种JavaScript方法可以检测设备是否具有触摸屏功能。我正在使用jquery-mobile.js来检测触摸屏事件,并且它在iOS、Android等设备上工作正常,但是我还想编写基于用户设备是否具有触摸屏的条件语句。
这种可能性存在吗?
我编写了一个适用于桌面和移动设备的jQuery插件。我想知道是否有一种JavaScript方法可以检测设备是否具有触摸屏功能。我正在使用jquery-mobile.js来检测触摸屏事件,并且它在iOS、Android等设备上工作正常,但是我还想编写基于用户设备是否具有触摸屏的条件语句。
这种可能性存在吗?
目前来看,这似乎对我很好用:
//Checks if a touch screen
is_touch_screen = 'ontouchstart' in document.documentElement;
if (is_touch_screen) {
// Do something if a touch screen
}
else {
// Not a touch screen (i.e. desktop)
}
function isTouchDevice() {
var el = document.createElement('div');
el.setAttribute('ongesturestart', 'return;'); // or try "ontouchstart"
return typeof el.ongesturestart === "function";
}
上述解决方案基于无需浏览器嗅探即可检测事件支持文章。
您可以在以下测试页面中查看结果。
请注意,上述代码仅测试浏览器是否支持触摸,而不是设备。因此,如果您使用带有触摸屏的笔记本电脑,则您的浏览器可能不支持触摸事件。最近的Chrome支持触摸事件,但其他浏览器可能不支持。
您也可以尝试:
if (document.documentElement.ontouchmove) {
// ...
}
但在 iPhone 设备上可能无法正常工作。
扩展jQuery support
对象:
jQuery.support.touch = 'ontouchend' in document;
if( jQuery.support.touch )
// do touch stuff
$(".phoneBtn").on( "mousedown touchstart", function(event) {
if (event.type == "touchstart") {
pressButton(this);
$(this).off('mousedown');
//Only touchstart event is heard
} else if (event.type == "mousedown") {
$(this).off('touchstart');
pressButton(this);
//Only mousedown event is heard
}
)}
$.support.touch ? "true" : "false";
如果你测试document.documentElement是否支持touchstart,那么这很简单。
var x = 'touchstart' in document.documentElement;
console.log(x)
// return true if is supported
// else return false
尽管它只处于alpha阶段,但jquery移动框架值得一试。它将在移动浏览器中规范这些类型的事件。也许可以看看他们正在做什么。我假设jquery-mobile.js与此框架不同。
这种方式对我很有效,它等待第一次用户交互,以确保他们在触摸设备上
var touchEnabled = false;
$(document.body).one('touchstart',
function(e){
touchEnabled=true;
$(document.documentElement).addClass("touch");
// other touch related init
//
}
);