How to detect if a device has mouse support?

后端 未结 6 1247
猫巷女王i
猫巷女王i 2020-12-03 20:45

I currently use the following test (taken out of Modernizr) to detect touch support:

function is_touch_device() {
    var bool;
    if((\'ontouchstart\' in w         


        
6条回答
  •  情深已故
    2020-12-03 21:28

    There is no immediate way of knowing, you'll have to wait for a touch event or a mouse event.

    Presuming you want to detect either mouse or touch you can do the following: listen for touchstart and mousemove (the latter can fire on touch devices without an actual mouse). Whichever one fires first is 99% bound to be what you're looking for.

    This does not take in account devices that actually have both.

    document.addEventListener('mousemove', onMouseMove, true)
    document.addEventListener('touchstart', onTouchStart, true)
    function onTouchStart(){
      removeListeners()
      // touch detected: do stuff
    }
    function onMouseMove(){
      removeListeners()
      // mouse detected: do stuff
    }
    function removeListeners(){
      document.removeEventListener('mousemove', onMouseMove, true)
      document.removeEventListener('touchstart', onTouchStart, true)
    }
    

提交回复
热议问题