【发布时间】:2011-09-09 21:26:26
【问题描述】:
有没有什么好用又干净的方法或技巧来判断用户是否在触摸设备上?
我知道有类似的东西
var isiPad = navigator.userAgent.match(/iPad/i) != null;
但我只是想知道是否有一种技巧可以普遍确定用户是否在触摸设备上? 因为除了 iPad 之外,还有更多的触控设备和平板电脑。
谢谢。
【问题讨论】:
标签: javascript jquery touch tablet
有没有什么好用又干净的方法或技巧来判断用户是否在触摸设备上?
我知道有类似的东西
var isiPad = navigator.userAgent.match(/iPad/i) != null;
但我只是想知道是否有一种技巧可以普遍确定用户是否在触摸设备上? 因为除了 iPad 之外,还有更多的触控设备和平板电脑。
谢谢。
【问题讨论】:
标签: javascript jquery touch tablet
可以使用以下JS函数:
function isTouchDevice() {
var el = document.createElement('div');
el.setAttribute('ongesturestart', 'return;'); // or try "ontouchstart"
return typeof el.ongesturestart === "function";
}
来源:Detecting touch-based browsing。
请注意,上面的代码只测试浏览器是否支持触摸,而不是设备。
相关链接:
jquery for mobile和jtouch可能有检测
【讨论】:
alert(typeof el.ongesturestart) 或者你尝试了什么?什么设备?什么操作系统?在没有建设性信息的情况下投票对任何人都没有帮助。这也是一个2岁的帖子。自从
包括modernizer,这是一个很小的特征检测库。然后你可以使用类似下面的东西。
if (Modernizr.touch){
// bind to touchstart, touchmove, etc and watch `event.streamId`
} else {
// bind to normal click, mousemove, etc
}
【讨论】:
if ("ontouchstart" in document.documentElement)
{
alert("It's a touch screen device.");
}
else
{
alert("Others devices");
}
我在这里和那里浏览了很多后发现的最简单的代码
【讨论】:
使用document.createEvent("TouchEvent") 将无法在桌面设备上使用。所以你可以在 if 语句中使用它。
请注意,此方法可能会在非触控设备上产生错误。我更喜欢在document.documentElement 中检查ontouchstart。
【讨论】:
查看这个post,它提供了一个非常棒的代码 sn-p,用于说明检测到触摸设备时的操作或调用 touchstart 事件时的操作:
$(function(){
if(window.Touch) {
touch_detect.auto_detected();
} else {
document.ontouchstart = touch_detect.surface;
}
}); // End loaded jQuery
var touch_detect = {
auto_detected: function(event){
/* add everything you want to do onLoad here (eg. activating hover controls) */
alert('this was auto detected');
activateTouchArea();
},
surface: function(event){
/* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
alert('this was detected by touching');
activateTouchArea();
}
}; // touch_detect
function activateTouchArea(){
/* make sure our screen doesn't scroll when we move the "touchable area" */
var element = document.getElementById('element_id');
element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
/* modularize preventing the default behavior so we can use it again */
event.preventDefault();
}
【讨论】:
如果你使用Modernizr,如前所述,使用Modernizr.touch非常容易。
但是,为了安全起见,我更喜欢结合使用 Modernizr.touch 和用户代理测试。
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.touch函数替换为('ontouchstart' in document.documentElement)
另请注意,测试用户代理 iemobile 将提供比 Windows Phone 更广泛的检测到的 Microsoft 移动设备。
【讨论】: