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

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

    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...

提交回复
热议问题