What's the best way to detect a 'touch scr

2018-12-31 04:30发布

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 capability. I'm using jquery-mobile.js to detect the touch screen events and it works on iOS, Android etc., but I'd also like to write conditional statements based on whether the user's device has a touch screen.

Is that possible?

30条回答
孤独寂梦人
2楼-- · 2018-12-31 04:42

jQuery v1.11.3

There is a lot of good information in the answers provided. But, recently I spent a lot of time trying to actually tie everything together into a working solution for the accomplishing two things:

  1. Detect that the device in use is a touch screen type device.
  2. Detect that the device was tapped.

Besides this post and Detecting touch screen devices with Javascript, I found this post by Patrick Lauke extremely helpful: https://hacks.mozilla.org/2013/04/detecting-touch-its-the-why-not-the-how/

Here is the code...

$(document).ready(function() {
//The page is "ready" and the document can be manipulated.

    if (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0))
    {
      //If the device is a touch capable device, then...
      $(document).on("touchstart", "a", function() {

        //Do something on tap.

      });
    }
    else
    {
      null;
    }
});

Important! The *.on( events [, selector ] [, data ], handler ) method needs to have a selector, usually an element, that can handle the "touchstart" event, or any other like event associated with touches. In this case, it is the hyperlink element "a".

Now, you don't need to handle the regular mouse clicking in JavaScript, because you can use CSS to handle these events using selectors for the hyperlink "a" element like so:

/* unvisited link */
a:link 
{

}

/* visited link */
a:visited 
{

}

/* mouse over link */
a:hover 
{

}

/* selected link */
a:active 
{

}

Note: There are other selectors as well...

查看更多
路过你的时光
3楼-- · 2018-12-31 04:43

We tried the modernizr implementation, but detecting the touch events is not consistent anymore (IE 10 has touch events on windows desktop, IE 11 works, because the've dropped touch events and added pointer api).

So we decided to optimize the website as a touch site as long as we don't know what input type the user has. This is more reliable than any other solution.

Our researches say, that most desktop users move with their mouse over the screen before they click, so we can detect them and change the behaviour before they are able to click or hover anything.

This is a simplified version of our code:

var isTouch = true;
window.addEventListener('mousemove', function mouseMoveDetector() {
    isTouch = false;
    window.removeEventListener('mousemove', mouseMoveDetector);
});
查看更多
伤终究还是伤i
4楼-- · 2018-12-31 04:43

This one works well even in Windows Surface tablets !!!

function detectTouchSupport {
msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture,
touchSupport = (( "ontouchstart" in window ) || msGesture || window.DocumentTouch &&     document instanceof DocumentTouch);
if(touchSupport) {
    $("html").addClass("ci_touch");
}
else {
    $("html").addClass("ci_no_touch");
}
}
查看更多
倾城一夜雪
5楼-- · 2018-12-31 04:44

Have you tried using this function? (This is the same as Modernizr used to use.)

function is_touch_device() {  
  try {  
    document.createEvent("TouchEvent");  
    return true;  
  } catch (e) {  
    return false;  
  }  
}

UPDATE 1

document.createEvent("TouchEvent") have started to return true in the latest chrome (v. 17). Modernizr updated this a while ago. Check Modernizr test out here.

Update your function like this to make it work:

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

UPDATE 2

I found that the above wasn't working on IE10 (returning false on MS Surface). Here is the fix:

function is_touch_device() {
  return 'ontouchstart' in window        // works on most browsers 
      || 'onmsgesturechange' in window;  // works on IE10 with some false positives
};

UPDATE 3

'onmsgesturechange' in window will return true in some IE desktop versions so thats not reliable. This works slightly more reliably:

function is_touch_device() {
  return 'ontouchstart' in window        // works on most browsers 
      || navigator.maxTouchPoints;       // works on IE10/11 and Surface
};

UPDATE 2018

Time goes by and there are new and better ways to test this. I've basically extracted and simplified Modernizr's way of checking it:

function is_touch_device() {
  var prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
  var mq = function(query) {
    return window.matchMedia(query).matches;
  }

  if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
    return true;
  }

  // include the 'heartz' as a way to have a non matching MQ to help terminate the join
  // https://git.io/vznFH
  var query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join('');
  return mq(query);
}

Here they are using the non-standard touch-enabled media query feature, which I think is kinda weird and bad practice. But hey, in the real world I guess it works. In the future (when they are supported by all) those media query features could give you the same results: pointer and hover.

Check out the source of how Modernizr are doing it.

For a good article that explains the issues with touch detection, see: Stu Cox: You Can't Detect a Touchscreen.

查看更多
步步皆殇っ
6楼-- · 2018-12-31 04:44

Using all the comments above I've assembled the following code that is working for my needs:

var isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));

I have tested this on iPad, Android (Browser and Chrome), Blackberry Playbook, iPhone 4s, Windows Phone 8, IE 10, IE 8, IE 10 (Windows 8 with Touchscreen), Opera, Chrome and Firefox.

It currently fails on Windows Phone 7 and I haven't been able to find a solution for that browser yet.

Hope someone finds this useful.

查看更多
倾城一夜雪
7楼-- · 2018-12-31 04:44

I also struggled a lot with different options on how to detect in Javascript whether the page is displayed on a touch screen device or not. IMO, as of now, no real option exists to detect the option properly. Browsers either report touch events on desktop machines (because the OS maybe touch-ready), or some solutions don't work on all mobile devices.

In the end, I realized that I was following the wrong approach from the start: If my page was to look similar on touch and non-touch devices, I maybe shouldn't have to worry about detecting the property at all: My scenario was to deactivate tooltips over buttons on touch devices as they lead to double-taps where I wanted a single tap to activate the button.

My solution was to refactor the view so that no tooltip was needed over a button, and in the end I didn't need to detect the touch device from Javascript with methods that all have their drawbacks.

查看更多
登录 后发表回答