我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
当前回答
这个即使在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");
}
}
其他回答
这个即使在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");
}
}
我喜欢这个:
function isTouchDevice(){
return window.ontouchstart !== undefined;
}
alert(isTouchDevice());
有一种方法比检查他们是否拥有触摸屏更好,那就是检查他们是否正在使用触摸屏,而且这更容易检查。
if (window.addEventListener) {
var once = false;
window.addEventListener('touchstart', function(){
if (!once) {
once = true;
// Do what you need for touch-screens only
}
});
}
当连接鼠标时,可以假设有相当高的点击率(我想说几乎100%),用户在页面准备好后移动鼠标至少一小段距离-没有任何点击。下面的机制检测到这一点。如果检测到,我认为这是缺少触摸支持的标志,或者,如果支持,在使用鼠标时不太重要。如果未检测到触摸设备,则假定为触摸设备。
这种方法可能不适合所有目的。它可以用来控制基于加载页面上的用户交互激活的功能,例如图像查看器。下面的代码还将把mouemove事件绑定在没有鼠标的设备上,因为它现在很突出。其他方法可能更好。
大致是这样的(对jQuery来说很抱歉,但在纯Javascript中类似):
var mousedown, first, second = false;
var ticks = 10;
$(document).on('mousemove', (function(e) {
if(UI.mousechecked) return;
if(!first) {
first = e.pageX;
return;
}
if(!second && ticks-- === 0) {
second = e.pageX;
$(document).off('mousemove'); // or bind it to somewhat else
}
if(first && second && first !== second && !mousedown){
// set whatever flags you want
UI.hasmouse = true;
UI.touch = false;
UI.mousechecked = true;
}
return;
}));
$(document).one('mousedown', (function(e) {
mousedown = true;
return;
}));
$(document).one('mouseup', (function(e) {
mousedown = false;
return;
}));
var isTouchScreen = 'createTouch' in document;
or
var isTouchScreen = 'createTouch' in document || screen.width <= 699 ||
ua.match(/(iPhone|iPod|iPad)/) || ua.match(/BlackBerry/) ||
ua.match(/Android/);
我想会进行更彻底的检查。