[javascript]如合判斷是否是mobile device

有關網頁及相關語法的討論
回覆文章
頭像
tim
文章: 1379
註冊時間: 2008年 11月 26日, 00:49

[javascript]如合判斷是否是mobile device

文章 tim »

1. 使用 user agent 配合 regular expression:

代碼: 選擇全部

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 // You are in mobile browser
}
2. 使用 user agent 逐一判斷(區分 android/iOS 等):

代碼: 選擇全部

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

if(isMobile.any()) {
   // It is mobile
}

3. 使用 TouchEvent 配合 try catch:

代碼: 選擇全部

function isMobile() {
  try{ document.createEvent("TouchEvent"); return true; }
  catch(e){ return false; }
}
參考資料: http://magentohostsolution.com/3-ways-d ... ce-jquery/

TAG: mobile, detect
多多留言, 整理文章, 把經驗累積下來.....
回覆文章