How to test for Touch-Events now that Chrome fails standard tests?

倾然丶 夕夏残阳落幕 提交于 2019-11-28 20:49:19

Short answer: Your test will work again now in any current of Chrome. But probably not forever.

Long answer:

The Chrome team wanted to add touch events into desktop browsers, because of the growing number of desktops with touch-capable screens. So they did - probably around the time of 24.0 Canary. They then found that loads of people were doing what you're doing to "detect touch devices". The problem with this is you're only testing if the browser supports touch events, not the device (same goes for Modernizr.touch). More specifically, just the W3C/Apple TouchEvents API.

They didn't want to ship different versions of Chrome for touch/non-touch, so they made it so they only enable the touch APIs if they detect a touch device on startup (discussed here: http://code.google.com/p/chromium/issues/detail?id=152149).

So now your test will work again... BUT - if you want to future-proof yourself, you might want to change your approach. Here's why:

  1. Not all browsers will perform this switch that Chrome does.

  2. Touch capability is becoming a dynamic feature: with Microsoft Surface etc you can unplug from keyboard and mouse and go touch-only, users may have touch monitors connected via KVM switches which won't be detected at startup, etc. Browser vendors don't want to make APIs appear and disappear - that'd be a nightmare - so at some point the Chrome guys will probably permanently enable the TouchEvents APIs on all devices. That test will start throwing "false positives" again.

Instead, look at the PointerEvents API, which gives a common event interface for mouse, touch and stylus inputs. If you're thinking of making buttons bigger for touch interfaces etc, there's a pointer media query spec too (and a hover one), which will appear in browsers soon - this differentiates between different accuracies of input devices - none/coarse/fine - and being dynamic will let you adjust your styles based on the connected pointer devices, as they're connected/disconnected. Very cool.

Modernizr v3.0 (dropping within the next few weeks) will have a couple of relevant changes here:

  • A detect for the PointerEvents API is being added
  • Modernizr.touch is being renamed Modernizr.touchevents to better represent what it means

So I'd consider using PointerEvents if available (which it already is in IE10), falling back to a Modernizr.touchevents switch if not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!