What's the best way to detect a 'touch screen' device using JavaScript?

后端 未结 30 2494
花落未央
花落未央 2020-11-21 23:50

I\'ve written a jQuery plug-in that\'s for use on both desktop and mobile devices. I wondered if there is a way with JavaScript to detect if the device has touch screen capa

30条回答
  •  忘了有多久
    2020-11-22 00:16

    Since the introduction of interaction media features you simply can do:

    if(window.matchMedia("(pointer: coarse)").matches) {
        // touchscreen
    }
    

    https://www.w3.org/TR/mediaqueries-4/#descdef-media-any-pointer

    Update (due to comments): The above solution is to detect if a "coarse pointer" - usually a touch screen - is the primary input device. In case you want to dectect if a device with e.g. a mouse also has a touch screen you may use any-pointer: coarse instead.

    For more information have a look here: Detecting that the browser has no mouse and is touch-only

提交回复
热议问题