如何检测设备是否支持鼠标?

我目前使用以下测试(取自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; } 

但有些设备是触摸和鼠标驱动的,所以我想要一个单独的function来检测设备是否有鼠标支持。 有什么好办法做这个检查?

最终我的意图是能够做到这些:

 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之后,该值才会正确,因此无法信任在页面加载时使用。

正如问题评论中所提到的,特别是在https://github.com/Modernizr/Modernizr/issues/869上 ,还没有好的答案。

有一个CSS媒体就是为了这个!

您可以通过获取pointer CSS媒体function的值来检查某些设备是否有鼠标:

 if (matchMedia('(pointer:fine)').matches) { // Device has a mouse } 

因为它是CSS,你甚至不需要使用JavaScript:

 @media (pointer: fine) { /* Rules for devices with mouse here */ } 
 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/

没有直接的了解方法,您将不得不等待触摸事件或鼠标事件。

假设您想要检测鼠标触摸,您可以执行以下操作:监听touchstartmousemove (后者可以在没有实际鼠标的情况下触摸触摸设备)。 无论哪一个首先发射,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) }