admin管理员组

文章数量:1430078

Is it okay to do the following to determine if you are on mobile device?

if(window.Touch != undefined) 
{
   //redirect to my mobile site
}

I would like to do a small check to see if its a mobile device. I don't want to import modernizr library just for this simple check.

Is it okay to do the following to determine if you are on mobile device?

if(window.Touch != undefined) 
{
   //redirect to my mobile site
}

I would like to do a small check to see if its a mobile device. I don't want to import modernizr library just for this simple check.

Share Improve this question asked Oct 20, 2011 at 2:03 dev.e.loperdev.e.loper 36.1k77 gold badges167 silver badges257 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

This is what I do and so far it has worked pretty well:

var HAS_TOUCH = ('ontouchstart' in window);

I'm using:

if(window.MSPointerEvent){
    //you are on IE10
}else if(window.PointerEvent){
    //you are on IE11
}else if(window.TouchEvent){
    //android and safari
}else{
    //don't have touch events
}

I tested this on Android 2.3 and 4.4.2 and on iOS 7.1. For the IE I used what Microsoft remended

Using TouchEvent only works if you are on a touch device; that doesn't mean a mobile device. For that use a regular expression on the userAgent:

if(navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i)){
    //you are on Android or iPhone
}

But there are a lot of other cases to treat, for example, Windows Phone and BlackBerry, so I remend using the detect mobile API.

Okay found something after extensive search. window.touch doesn't work on Android at least that is what someone has said. I can't confirm since I don't have a mobile device that runs Android

本文标签: javascriptUsing windowTouch to find out if current device is a mobile deviceStack Overflow