[javascript]如合判斷是否是mobile device
發表於 : 2015年 9月 17日, 12:26
1. 使用 user agent 配合 regular expression:
2. 使用 user agent 逐一判斷(區分 android/iOS 等):
3. 使用 TouchEvent 配合 try catch:
參考資料: http://magentohostsolution.com/3-ways-d ... ce-jquery/
TAG: mobile, detect
代碼: 選擇全部
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// You are in mobile browser
}
代碼: 選擇全部
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; }
}
TAG: mobile, detect