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

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

    Actually, I researched this question and consider all situations. because it is a big issue on my project too. So I reach the below function, it works for all versions of all browsers on all devices:

    const isTouchDevice = () => {
      const prefixes = ['', '-webkit-', '-moz-', '-o-', '-ms-', ''];
      const mq = query => window.matchMedia(query).matches;
    
      if (
        'ontouchstart' in window ||
        (window.DocumentTouch && document instanceof DocumentTouch)
      ) {
        return true;
      }
      return mq(['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''));
    };
    

    Hint: Definitely, the isTouchDevice just returns boolean values.

提交回复
热议问题