javascript detect desktop touch and mouse support

2019-07-05 17:06发布

问题:

How should touch-enabled devices be differentiates between pure touch and ones that also have a mouse? (like some of today's laptops)

There is a need to give all mouse functionality a priority in an application, and if the device running the app has only touch support, to change the functionality.

If a touch-device also has a mouse pointer, logic suggests the app should consider that device as a normal desktop, and might add touch support as well, but the styling itself should respond to mouse events.

normal touch detection is achieved like so: 'ontouchend' in document;

One way to detect if the computer is desktop might be to check the screen resolution:

window.screen.width >= 1280 // desktop 

but that is not so good because some devices might have very large viewport resolution, and some laptops might have low resolution...

回答1:

After some research, I have found that the best solution was to use this code:

https://github.com/matthewhudson/device.js

So, the way it works, is by giving the body element class names which represent the device and orientation, and with that I can pretty much guess if the user has a mouse. (class desktop is applied)