我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
当前回答
虽然它只是alpha版本,但jquery移动框架值得一试。它将在移动浏览器中规范化这些类型的事件。也许可以看看他们在做什么。我假设jquery-mobile.js与这个框架有所不同。
其他回答
这个即使在Windows Surface平板电脑上也能很好地工作!!
function detectTouchSupport {
msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture,
touchSupport = (( "ontouchstart" in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch);
if(touchSupport) {
$("html").addClass("ci_touch");
}
else {
$("html").addClass("ci_no_touch");
}
}
所以关于检测触摸/非触摸设备存在很大的争议。窗口平板电脑的数量和尺寸都在增加,这给我们网页开发者带来了另一个难题。
我已经使用并测试了blmstr的菜单答案。菜单的工作方式是这样的:当页面加载时,脚本检测这是一个触摸或非触摸设备。基于此,菜单将在悬停(非触摸)或点击/点击(触摸)时工作。
在大多数情况下,blmstr的脚本似乎工作得很好(特别是2018年的那个)。但仍然有一种设备,当它不是触摸时,它会被检测为触摸,反之亦然。
出于这个原因,我做了一些挖掘,多亏了这篇文章,我从blmstr的第4个脚本中替换了几行:
函数is_touch_device4() { If ("ontouchstart" in window) 返回true; 如果窗口。DocumentTouch的文档实例) 返回true; 返回窗口。matchMedia("(指针:粗)").matches; } alert('Is touch device: '+is_touch_device4()); console.log('Is touch device: '+is_touch_device4());
由于封锁,有有限的触摸设备来测试这一个,但到目前为止,上面的工作很好。
如果任何人有桌面触摸设备(如平板电脑)可以确认脚本是否工作正常,我将不胜感激。
现在在支持指针方面:粗媒体查询似乎是支持的。我保留了上面的行,因为我在移动firefox上(出于某种原因)出现了问题,但媒体查询上面的行是有效的。
谢谢
这种方法对我来说很有效,它等待第一次用户交互,以确保他们是在触摸设备上
var touchEnabled = false;
$(document.body).one('touchstart',
function(e){
touchEnabled=true;
$(document.documentElement).addClass("touch");
// other touch related init
//
}
);
工作小提琴
我是这样做到的;
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 isTouchDevice =
(('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
if(!isTouchDevice){
/* Code for touch device /*
}else{
/* Code for non touch device */
}