以前在JavaScript中检测设备是否支持触摸事件时,我们可以这样做:
var touch_capable = ('ontouchstart' in document.documentElement);
但是,Google Chrome (17.x.x+) 会为上述检查返回
true
,即使底层设备不支持触摸事件。例如,在 Windows 7 上运行上面的代码会返回 true,因此如果我们将它与类似的东西结合起来:
var start_evt = (touch_capable) ? 'ontouchstart' : 'onmousedown';
在谷歌浏览器上,事件永远不会被触发,因为我们绑定到
ontouchstart
。简而言之,有谁知道规避这种情况的可靠方法吗?我目前正在运行以下检查:
var touch_capable = ('ontouchstart' in document.documentElement && navigator.userAgent.toLowerCase().indexOf('chrome') == -1)
这远非理想......
正确的答案是处理 both 事件类型——它们并不相互排斥。
对于更可靠的触摸支持测试,还可以寻找
window.DocumentTouch && document instanceof DocumentTouch
,这是 Modernizr 使用的测试之一
更好的是,您自己使用 Modernizr 并让它为您进行特征检测。
请注意,尽管您无法防止误报,因此我在上面的第一行 - 您got 支持两者。
这是对 Modernizr 执行触摸检测方式的修改,增加了对 IE10+ 触摸设备的支持。
const isTouchCapable = 'ontouchstart' in window ||
(window.DocumentTouch && document instanceof window.DocumentTouch) ||
navigator.maxTouchPoints > 0 ||
window.navigator.msMaxTouchPoints > 0;
这不是万无一失的,因为检测触摸设备显然是不可能的.
您的里程可能会有所不同:
更新: 提示:不要使用触摸功能检测来控制和指定 UI 行为,使用事件监听器。为点击/触摸/按键事件而不是设备设计,触摸功能检测通常用于节省添加事件侦听器的 cpu/内存开销。触摸检测可能有用且合适的示例之一:
if (isTouchCapable) {
document.addEventListener('touchstart', myTouchFunction, false);
}
const isTouchCapable = 'ontouchstart' in window ||
(window.DocumentTouch && document instanceof window.DocumentTouch) ||
navigator.maxTouchPoints > 0 ||
window.navigator.msMaxTouchPoints > 0;
const qualifier = isTouchCapable ? "IS" : "is NOT";
alert(`Your browser/device ${qualifier} currently capable of recieving touch events.`)
您应该考虑使用经过良好测试(和跨浏览器)的 Modernizr 的触摸测试。
来自他们的网站:
// bind to mouse events in any case
if (Modernizr.touch){
// bind to touchstart, touchmove, etc and watch `event.streamId`
}
好老的问题,但是必须在没有图书馆的情况下这样做,我创建了以下解决方案——简单地让事件自己说话——当你看到
touch
事件时,只需禁用mouse
事件的处理.
在 coffesscript 中看起来像这样;
hasTouch = false
mouseIsDown = false
@divs.on "touchstart", (e)->
hasTouch = true
touchstart(e.timeStamp,e.originalEvent.touches[0].pageX);
return true
@divs.on "mousedown", (e)->
mouseIsDown = true;
touchstart(e.timeStamp,e.clientX) if not hasTouch
return true
@divs.on 'touchmove', (e) ->
touchmove(e.timeStamp,e.originalEvent.touches[0].pageX);
return true;
@divs.on 'mousemove', (e) ->
touchmove(e.timeStamp,e.clientX) if mouseIsDown and not hasTouch
return true;
@divs.on 'touchend', (e) ->
touchend();
return true
@divs.on 'mouseup', (e) ->
mouseIsDown = false;
touchend() if not hasTouch
return true
只需为
touchstart
、move
和end
定义函数,包含实际逻辑....