如何在2019年检测触摸设备? [英] How to detect touch device in 2019?

查看:82
本文介绍了如何在2019年检测触摸设备?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的应用程序,我需要使用屏幕键盘(例如,移动设备,触摸电视)与鼠标/kbd设备(例如,台式机,带有蓝牙鼠标/kbd的移动设备)彻底改变触摸设备的整个UX.

For my app, I need to radically change the entire UX for touch devices using an onscreen keyboard (eg. mobile, touch TV) vs mouse/kbd devices (eg. desktop, a mobile with a bluetooth mouse/kbd).

NB.我已经在CSS网格和媒体查询中使用了响应式布局,因此可以解决该方面的问题.我的问题不是布局之一,而是整个UX需要根本不同.到目前为止,我最好的选择是在整个视口上监听鼠标移动.

NB. I've already grokked responsive layout with CSS grid and media queries, so that aspect is dealt with. My issue isn't one of layout, it's that the entire UX needs to be fundamentally different. The best option I have so far is to listen for a mousemove on the whole viewport.

如何使用现代浏览器来做到这一点?

How can I do this using modern browsers?

请注意,我已经阅读了已有多年历史的现有答案,并且普遍认为这是不可能完成的.

Note I've already read the existing answers which are all several years old, and generally conclude that it can't be done.

推荐答案

这很简单,只需一行代码:

This is really simple with just one line of code:

const touch = matchMedia('(hover: none)').matches;

-什么? matchMedia?
-这只是执行CSS @media查询的JS API.它在现代浏览器中受支持: https://caniuse.com/#feat=matchmedia .当然,您可以直接在CSS中使用此类查询:

- What? matchMedia?
- This is just a JS API to do CSS @media queries. And it is supported in modern browsers: https://caniuse.com/#feat=matchmedia. Of course, you may use such queries directly in CSS:

@media (hover: none){
    /* touch stuff goes here */
}

-好的,哪些@media查询也可能有用?

- Ok, what @media queries may be also useful?

@media (hover: none) and (pointer: coarse) {
    /* touchscreens */
}
@media (hover: none) and (pointer: fine) {
    /* stylus */
}
@media (hover: hover) and (pointer: coarse) {
    /* controllers */
}
@media (hover: hover) and (pointer: fine) {
    /* mouse or touchpad */
}

但是这只会查询主要输入法.如果您想更深入一点,可以使用any-hoverany-pointer查询所有输入设备.

But this will query only the primary input method. If you want to go deeper, you may use any-hover and any-pointer to query all input devices.

UPD:删除了旧浏览器的hack,似乎大多数旧浏览器也不支持hoverpointer媒体查询.您可以使用触摸事件检测和其他答案的仅触摸navigator属性

UPD: hack for old browsers removed, seems like most old browsers does not support hover and pointer media queries too. You may use touch event detection and touch-only navigator properties from another answers

UPD2:根据您的情况,最好使用

UPD2: In your case, it's preferable to use

const touch = matchMedia('(hover: none), (pointer: coarse)').matches;

这篇关于如何在2019年检测触摸设备?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆