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

后端 未结 30 2467
花落未央
花落未央 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:18

    Many of these work but either require jQuery, or javascript linters complain about the syntax. Considering your initial question asks for a "JavaScript" (not jQuery, not Modernizr) way of solving this, here's a simple function that works every time. It's also about as minimal as you can get.

    function isTouchDevice() {
        return !!window.ontouchstart;
    }
    
    console.log(isTouchDevice());
    

    One last benefit I'll mention is that this code is framework and device agnostic. Enjoy!

提交回复
热议问题