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

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

    If you use Modernizr, it is very easy to use Modernizr.touch as mentioned earlier.

    However, I prefer using a combination of Modernizr.touch and user agent testing, just to be safe.

    var deviceAgent = navigator.userAgent.toLowerCase();
    
    var isTouchDevice = Modernizr.touch || 
    (deviceAgent.match(/(iphone|ipod|ipad)/) ||
    deviceAgent.match(/(android)/)  || 
    deviceAgent.match(/(iemobile)/) || 
    deviceAgent.match(/iphone/i) || 
    deviceAgent.match(/ipad/i) || 
    deviceAgent.match(/ipod/i) || 
    deviceAgent.match(/blackberry/i) || 
    deviceAgent.match(/bada/i));
    
    if (isTouchDevice) {
            //Do something touchy
        } else {
            //Can't touch this
        }
    

    If you don't use Modernizr, you can simply replace the Modernizr.touch function above with ('ontouchstart' in document.documentElement)

    Also note that testing the user agent iemobile will give you broader range of detected Microsoft mobile devices than Windows Phone.

    Also see this SO question

提交回复
热议问题