如何确定客户端是否为触控设备
是否有任何漂亮和干净的方法或技巧,以确定用户是否在触摸设备上?
我知道有像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"; }
来源: 检测基于触摸的浏览 。
请注意,上述代码仅测试浏览器是否支持触摸,而不支持设备。
相关链接:
- 优化触摸设备的网站
- 在jQuery中检测移动设备的最佳方法是什么?
- 使用JavaScript检测“触摸屏”设备的最佳方法是什么?
- Mozilla.org检测触摸:它是’为什么’,而不是’如何’
可能在jquery中检测到移动和jtouch
if ("ontouchstart" in document.documentElement) { alert("It's a touch screen device."); } else { alert("Others devices"); }
我在这里和那里浏览了很多之后找到的最简单的代码
包括现代化器 ,这是一个微小的特征检测库。 然后你可以使用下面的东西。
if (Modernizr.touch){ // bind to touchstart, touchmove, etc and watch `event.streamId` } else { // bind to normal click, mousemove, etc }
使用document.createEvent("TouchEvent")
将无法在桌面设备上运行。 所以你可以在if语句中使用它。
请注意,此方法可能会在非触摸设备上产生错误。 我更愿意在document.documentElement
检查ontouchstart
。
看看这篇文章 ,它提供了一个非常好的代码片段,用于检测触摸设备时的操作或调用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移动设备。
另见这个问题