-->

Javascript, detect touch devices

2020-07-17 07:10发布

问题:

I'm using this function to detect if the device is a touch device:

function is_touch_device()
{
    return !!('ontouchstart' in window) || !!('onmsgesturechange' in window);
};

Got this function from here: What's the best way to detect a 'touch screen' device using JavaScript?

But since Chrome 25 (25.0.1364) it returns true on my desktop which isn't a touch device. Also I've updated IE9 to IE10 and it returns true in IE!

Searched around but couldn't find anything useful to fix this except using a something like this: http://detectmobilebrowsers.com/

What do you recommend?

I'm looking forward to your responses!

回答1:

The code works just fine, the browser is able to understand touch events, just because your screen isn't touchable doesn't mean that the browser doesn't support the functionality. What you are looking to test is a hardware capability which isn't really testable. You can always use different ways though of seeing if the user is actual using a touch interface after touching it once, such as this article describes, or many others that larger libraries use such as Modernizer.

As a reference the code actually used in the article above is:

function isTouchDevice() {
   var el = document.createElement('div');
   el.setAttribute('ongesturestart', 'return;');
   if(typeof el.ongesturestart == "function"){
      return true;
   }else {
      return false
   }
}


回答2:

This seems to work:

function isTouchEnabled() { return !!document.createTouch; }


回答3:

You could use Modernizr to detect touch capability.

This question is very similar to What's the best way to detect a 'touch screen' device using JavaScript? and should perhaps be considered a duplicate.



回答4:

i was experiencing a false positive IE10 touch issue as well when I was visiting the site i've been working on from my laptop. The original is_touch_device method, i used basically the same thing. I modified the latter half of that statement to be the following:

function is_touch_device()
{
    return !!('ontouchstart' in window) || (!!('onmsgesturechange' in window) && !!window.navigator.maxTouchPoints);
}

window.navigator.maxTouchPoints seems to be something specific in IE10 based on this post: http://msdn.microsoft.com/en-us/library/hh772144(v=vs.85).aspx



回答5:

You can use 51dergees.mobi for detection on the server appropriately changing page view. It has HasTouchScreen, IsSmartPhone, IsTablet properties etc.