在做響應式設計或行動版網頁時,經常需要判斷使用者是否使用行動裝置,以及裝置的類型。以下提供幾個實用的判斷函式。
可以綜合螢幕寬度與是否為觸控螢幕來判斷:
function isMobile(){
if (typeof this._isMobile === 'boolean'){
return this._isMobile;
}
var screenWidth = this.getScreenWidth();
var isMobileScreenSize = screenWidth < 600;
this._isMobile = isMobileScreenSize && this.isTouchScreen();
return this._isMobile;
}
透過 userAgent 比對關鍵字:
function isMobileUserAgent(){
return (/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.userAgent.toLowerCase()));
}
function isAppleMobileDevice(){
return (/iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase()));
}
function isAndroidMobileDevice(){
return (/android/i.test(navigator.userAgent.toLowerCase()));
}
透過這些函式,就能靈活判斷使用者所使用的裝置類型,進而給出對應的版面或功能。其中 userAgent 比對是最常用的方式,而結合螢幕寬度與觸控偵測則能讓判斷更準確。