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:
Not all browsers will perform this switch that Chrome does.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…