看来你真的想要做的是测试支持触控,尝试Detecting touch: it’s the ‘why’, not the ‘how’。
一个共同的建议是:
if (document && document.element && 'ontouchstart' in document.documentElement) {
...
}
但是,很可能在某些浏览器中失败。较长的方法,虽然可能没有更准确,是测试活动的支持直接:
/* Feature tests for TouchEvent and GestureEvent modules
* implemented in Mobile Safari on iPhone
*
* The TouchEvent module is a draft (18/08/2008) that supports:
*
* touchstart
* touchmove
* touchend
* touchcancel
*
* The GestureEvent module is a draft (18/08/2008)
* that supports:
*
* gesturestart
* gesturechange
* gestureend
*
* The functions require support for try..catch, introduced
* in ECMA-262 ed3, JavaScript 1.4 and JScript 5.1.5010.
* Equates to Navigator 4.0 or later and IE 5.1 or later
* (http://pointedears.de/scripts/es-matrix/)
*
* If W3C DOM 2 Event document.createEvent is supported,
* return either true or false,
* otherwise return undefined.
*/
function touchSupported() {
if (document && document.createEvent) {
try {
document.createEvent('TouchEvent');
return true;
} catch (e) {
return false;
}
}
}
function gestureSupported() {
if (document && document.createEvent) {
try {
document.createEvent('GestureEvent');
return true;
} catch (e) {
return false;
}
}
}
这是写在2008年,我才真正用它在Safari和iPhone虽然它似乎在其他地方工作。彻底测试。
在我看来,你的问题是触摸用户界面与光标用户界面,这不一定与移动设备和PC(大概是桌面)相关。也许提供光标(或指点设备)的触摸和设置的设置,并让用户选择一个或另一个。 – RobG
所以我做到了这一点(理论上听起来正确),但在实践中我该如何去做呢?我尝试使用Modernizr.touch来识别某些浏览器是否支持触摸,并且它不起作用(或者我不期望它如何工作)。 – a2zCribbage
我有一个简单的触摸支持功能测试,我会在几个小时后发布。 – RobG