有没有什么好的和干净的方法或技巧来确定用户是否在触摸设备上?
我知道有这样的东西
var isiPad = navigator.userAgent.match(/iPad/i) != null;
但我只是想知道是否有一种技巧可以大致确定用户是否使用 Touch 设备?因为有更多的触摸设备和平板电脑,然后只有 iPad。
谢谢。
有没有什么好的和干净的方法或技巧来确定用户是否在触摸设备上?
我知道有这样的东西
var isiPad = navigator.userAgent.match(/iPad/i) != null;
但我只是想知道是否有一种技巧可以大致确定用户是否使用 Touch 设备?因为有更多的触摸设备和平板电脑,然后只有 iPad。
谢谢。
您可以使用以下 JS 函数:
function isTouchDevice() {
var el = document.createElement('div');
el.setAttribute('ongesturestart', 'return;'); // or try "ontouchstart"
return typeof el.ongesturestart === "function";
}
来源:检测基于触摸的浏览。
请注意上面的代码只测试浏览器是否支持触摸,而不是设备。
相关链接:
包括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 语句中使用它。
请注意,此方法可能会在非触摸设备上产生错误。我宁愿检查的ontouchstart
在document.documentElement
。
查看这篇文章,它提供了一个非常好的代码片段,用于说明在检测到触摸设备时要做什么或在调用 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();
}