我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
当前回答
如果您使用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问题
其他回答
如果您使用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问题
由于Modernizr无法检测Windows Phone 8/WinRT上的IE10,一个简单的跨浏览器解决方案是:
var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;
你只需要检查一次,因为设备不会突然支持或不支持触摸,所以只需将它存储在一个变量中,这样你就可以更有效地多次使用它。
许多这些工作,但要么需要jQuery,或javascript linters抱怨语法。考虑到你最初的问题要求“JavaScript”(不是jQuery,不是Modernizr)来解决这个问题,这里有一个简单的函数,每次都能工作。这也是你能得到的最小值。
function isTouchDevice() {
return !!window.ontouchstart;
}
console.log(isTouchDevice());
我要提到的最后一个好处是,该代码是框架和设备不可知的。享受吧!
事实上,我研究了这个问题并考虑了各种情况。因为这在我的项目中也是一个大问题。所以我达到了下面的功能,它适用于所有设备上所有浏览器的所有版本:
const isTouchDevice = () => {
const prefixes = ['', '-webkit-', '-moz-', '-o-', '-ms-', ''];
const mq = query => window.matchMedia(query).matches;
if (
'ontouchstart' in window ||
(window.DocumentTouch && document instanceof DocumentTouch)
) {
return true;
}
return mq(['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''));
};
提示:显然,isTouchDevice只返回布尔值。
工作小提琴
我是这样做到的;
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
}