javascript - 在触摸屏设备上检测鼠标

标签 javascript jquery touch

我使用下面的代码来检测设备是否是触摸设备:

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.

  1. 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.
  2. 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).
  3. 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.
  4. 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/

相关文章:

Javascript - 动态添加的复选框在 Kendo Panelbar 标题中没有按预期工作

java - Android同时触摸和触摸释放

Android 在触摸事件上移动 View

java - 触摸位置周围的半径

javascript - 使打开 1 div 关闭 JS/JQuery 中同一类的所有其他 div(不包括自身)?

javascript - 避免提交表单两次 Parsley - Jquery

Jquery 验证和 Prototypes.js 冲突问题?

jquery - 如何在一个文件中存储多个html模板?

javascript - 如何在node js中使用jimp在多个图像上打印不同的文本?

javascript - 将 jQuery 和 CSS3 滚动效果从功能垂直滚动转换为所需的水平滚动的问题