DIV CSS 佈局教程網

用 JS 判斷行動裝置類型
編輯:JavaScript基礎知識     

在做響應式設計或行動版網頁時,經常需要判斷使用者是否使用行動裝置,以及裝置的類型。以下提供幾個實用的判斷函式。

判斷是否為行動裝置

可以綜合螢幕寬度與是否為觸控螢幕來判斷:

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 比對是最常用的方式,而結合螢幕寬度與觸控偵測則能讓判斷更準確。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved