我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
当前回答
这种方法对我来说很有效,它等待第一次用户交互,以确保他们是在触摸设备上
var touchEnabled = false;
$(document.body).one('touchstart',
function(e){
touchEnabled=true;
$(document.documentElement).addClass("touch");
// other touch related init
//
}
);
其他回答
虽然它只是alpha版本,但jquery移动框架值得一试。它将在移动浏览器中规范化这些类型的事件。也许可以看看他们在做什么。我假设jquery-mobile.js与这个框架有所不同。
这种方法对我来说很有效,它等待第一次用户交互,以确保他们是在触摸设备上
var touchEnabled = false;
$(document.body).one('touchstart',
function(e){
touchEnabled=true;
$(document.documentElement).addClass("touch");
// other touch related init
//
}
);
如果你测试document.documentElement中支持touchstart,这就很简单了
var x = 'touchstart'在document.documentElement; console.log (x) //如果支持返回true //否则返回false
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/);
我想会进行更彻底的检查。
看起来Chrome 24现在支持触摸事件了,可能是Windows 8。所以这里发布的代码不再有效。而不是试图检测触摸是否支持浏览器,我现在绑定触摸和点击事件,并确保只有一个被调用:
myCustomBind = function(controlName, callback) {
$(controlName).bind('touchend click', function(e) {
e.stopPropagation();
e.preventDefault();
callback.call();
});
};
然后调用它:
myCustomBind('#mnuRealtime', function () { ... });
希望这能有所帮助!