在項目中常常會有須要判斷瀏覽器是不是手機端仍是PC端,這裏有2個函數 供參考:javascript
let isMobile = function() {
let userAgentInfo = navigator.userAgent.toLowerCase();
let Agents = new Array('android', 'iphone', 'symbianos', 'windows phone', 'ipad', 'ipod');
let flag = false;
for (let v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) !== -1) {
flag = true;
break;
}
}
return flag;
};
用法:java
let ismobileBool = isMobile(); android
//true 表明是手機端,false表明是PC端web
另一個函數也是能夠 用做判斷windows
var browserRedirect=function () {
var sUserAgent = navigator.userAgent.toLowerCase();
var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
var bIsMidp = sUserAgent.match(/midp/i) == "midp";
var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
var bIsAndroid = sUserAgent.match(/android/i) == "android";
var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
//若是是上述設備就會以手機域名打開
return 'mobile';
} else {
//不然就是電腦域名打開
return 'pc';
}
}
用法爲: var browser = browserRedirect();瀏覽器
//mobile 爲手機, pc爲PC端iphone