我使用下面的代码来检测设备是否是触摸设备:
var isTouchDevice = 'ontouchstart' in window || navigator.msMaxTouchPoints;
if(isTouchDevice)
{
$('body').addClass('yes-touch');
}
else
{
$('body').addClass('no-touch');
}
我用它来仅显示 :hover
不是触摸设备时的状态(因为大多数触摸设备将点击解释为悬停)。
.no-touch .element:hover {
color: red;
}
问题是,我们办公室的一台 PC 是一体式触摸屏 PC,这意味着使用鼠标时不会出现悬停状态。
有没有办法判断鼠标是否正在触摸屏设备上使用?换句话说,它应该在使用鼠标时应用 no-touch
类,在使用触摸屏时应用 yes-touch
类。
最佳答案
时至今日,还没有万无一失的铁定方法。 modernizr 人员,几乎是特征检测方面的专家,最近对此有如下说法:
https://github.com/Modernizr/Modernizr/issues/869#issuecomment-57891034
The end result of all of this is that you cannot detect a mouse use in a way that would conform to the level of reliability that Modernizr is credited with. For our intents and purposes, it is a undetectable.
If you, future traveler, wish to attempt to detect a mouse user, then the following is the best guide I can offer.
- Don't. Seriously. Just because a user has a "mouse" doesn't mean that they don't have multiple other forms of input. You should try really hard to avoid making any kind of UI/UX decision that changes based upon the idea of a mouse user being diametrically opposed to a touchscreen user (or any other kind, for that matter). Make things universal.
- If you have to, and only care about IE 10 and 11, then IE's PointerEvent would be worth checking out. Support is abysmal, outside of those two (and presumably future IE versions).
- You can attach a listener for a 'hover' event on the body, and if it is true, then the user probably has a mouse. The drawback with this approach include touch events briefly firing hover events on tap/touch, so you could get false positives.
- sniff for mobile user agents. This is a bad idea, and goes against the very core of Modernizr. Please don't do it.
所以对我来说,#1 几乎概括了它。但是,这回答了您的问题,但没有为您提供解决方案。您提到“办公室中的一台我们 PC...”这是否只是一个内部应用程序?我偶尔会遇到这样的情况,无论出于何种原因,内部特殊用途或一页纸可能需要进行一些单独处理(例如我们的一名员工拥有带有鼠标的基于触摸的 AIO)。然后我要做的是将 ?hasmouse
附加到 url 的末尾,并为用户提供指向书签的链接。然后在您的 var isTouchDevice 之后但在您的 if 之前的 javascript 中,插入此代码以撤消它:
if (location.search == '?hasmouse') {
isTouchDevice = false;
}
同样,这是一种仅供内部使用的简洁方式。
关于javascript - 在触摸屏设备上检测鼠标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28594445/