我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
当前回答
你可以安装modernizer并使用一个简单的触摸事件。这是非常有效的,工作在每一个设备上,我已经测试了它包括窗户表面!
我已经创建了一个jsFiddle
function isTouchDevice(){
if(Modernizr.hasEvent('touchstart') || navigator.userAgent.search(/Touch/i) != -1){
alert("is touch");
return true;
}else{
alert("is not touch");
return false;
}
}
其他回答
更新2021
要查看以前的答案,请查看历史记录。我决定从头开始,因为在保存历史的时候,它变得难以控制。
我最初的回答是,使用与Modernizr使用的相同功能可能是一个好主意,但这不再有效,因为他们删除了这个PR: https://github.com/Modernizr/Modernizr/pull/2432上的“touchevents”测试,因为这是一个令人困惑的主题。
话虽如此,这应该是一个相当好的检测浏览器是否具有“触摸功能”的方法:
function isTouchDevice() {
return (('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
}
但是对于比我更聪明的人写过的更高级的用例,我建议阅读这些文章:
斯图·考克斯:你无法检测触摸屏 触摸检测:它是“为什么”,而不是“如何” Patrick H. Lauke的敏感演讲
虽然它只是alpha版本,但jquery移动框架值得一试。它将在移动浏览器中规范化这些类型的事件。也许可以看看他们在做什么。我假设jquery-mobile.js与这个框架有所不同。
许多这些工作,但要么需要jQuery,或javascript linters抱怨语法。考虑到你最初的问题要求“JavaScript”(不是jQuery,不是Modernizr)来解决这个问题,这里有一个简单的函数,每次都能工作。这也是你能得到的最小值。
function isTouchDevice() {
return !!window.ontouchstart;
}
console.log(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
}
有一种方法比检查他们是否拥有触摸屏更好,那就是检查他们是否正在使用触摸屏,而且这更容易检查。
if (window.addEventListener) {
var once = false;
window.addEventListener('touchstart', function(){
if (!once) {
once = true;
// Do what you need for touch-screens only
}
});
}