我目前使用以下测试(取自Modernizr)来检测触摸支持:
function is_touch_device() {
var bool;
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function(node) {
bool = node.offsetTop === 9;
});
}
return bool;
}
但有些设备是触摸和鼠标驱动的,所以我想要一个单独的功能来检测设备是否有鼠标支持。有什么好办法做这个检查?
最终我的意图是能够做到这些:
if(is_touch_device())
if(has_mouse_support())
if(is_touch_device() && has_mouse_support())
我目前正在使用以下(jQuery),我还没有在特定设备上发现任何缺陷
$(window).bind('mousemove.hasMouse',function(){
$(window).unbind('.hasMouse');
agent.hasMouse=true;
}).bind('touchstart.hasMouse',function(){
$(window).unbind('.hasMouse');
agent.hasMouse=false;
});
说明:鼠标设备(也是触摸屏笔记本电脑)首先触发鼠标移动,然后才能触发touchstart并将hasMouse设置为TRUE。触摸设备(也就是例如触发鼠标移动的iOS)点击后首先点击触摸开始,然后鼠标移动。那么为什么hasMouse将设置为FALSE。
唯一的问题是这取决于用户交互,只有在鼠标移动或touchstart之后,该值才会正确,因此无法信任在页面加载时使用。
var clickHandler = (isMouseEventSupported('click') ? 'click' : 'touchstart');
function isMouseEventSupported(eventName) {
var element = document.createElement('div');
eventName = 'on' + eventName;
var isSupported = (eventName in element);
if (!isSupported) {
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] == 'function';
}
element = null;
return isSupported;
}
这是来自我的朋友/同事的代码,他的基础是: http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
有 CSS媒体 只是为了那个!
您可以通过获取值来检查某些设备是否有鼠标 pointer
CSS媒体功能:
if (matchMedia('(pointer:fine)').matches) {
// Device has a mouse
}
因为它是CSS,你甚至不需要使用JavaScript:
@media (pointer: fine) {
/* Rules for devices with mouse here */
}
没有直接的了解方法,您将不得不等待触摸事件或鼠标事件。
假设您想要检测 或 老鼠 要么 触摸你可以做到以下几点:倾听 touchstart
和 mousemove
(后者可以在没有实际鼠标的情况下触摸触摸设备)。无论哪一个首先发射,99%必然会成为你想要的。
这并不考虑实际具有两者的设备。
document.addEventListener('mousemove', onMouseMove, true)
document.addEventListener('touchstart', onTouchStart, true)
function onTouchStart(){
removeListeners()
// touch detected: do stuff
}
function onMouseMove(){
removeListeners()
// mouse detected: do stuff
}
function removeListeners(){
document.removeEventListener('mousemove', onMouseMove, true)
document.removeEventListener('touchstart', onTouchStart, true)
}