一、实现思路 8 U* y; U4 n5 f7 e8 z6 K
可以通过 JavaScript 来实现判断当前的设备类型:navigator 是 JavaScript 中的一个独立的对象,用于提供用户所使用的浏览器以及操作系统等信息,以 navigator 对象属性的形式来提供。所有浏览器都支持该对象。
6 O* N) Y2 X3 t+ j4 m; N, y 而 navigator 对象有一个 userAgent 属性,会返回用户的设备操作系统和浏览器的信息。 此时可以通过 userAgent 判断是 H5 浏览器还是 PC 浏览器。而 App 不能获取 Window 的浏览器对象 navigator 的。那么可以在之前判断是否存在 navigator,不存在即为 App。 ]% N# ?6 ? x4 {3 a4 y/ n4 z
function fIsMobile(){
return /Android|iPhone|iPad|iPod|BlackBerry|webOS|Windows Phone|SymbianOS|IEMobile|Opera Mini/i.test(navigator.userAgent);
} 或者:
1 c) E! H+ J( Q+ n- M, M function iswap() {
var uA = navigator.userAgent.toLowerCase();
var ipad = uA.match(/ipad/i) == "ipad";
var iphone = uA.match(/iphone os/i) == "iphone os";
var midp = uA.match(/midp/i) == "midp";
var uc7 = uA.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
var uc = uA.match(/ucweb/i) == "ucweb";
var android = uA.match(/android/i) == "android";
var windowsce = uA.match(/windows ce/i) == "windows ce";
var windowsmd = uA.match(/windows mobile/i) == "windows mobile";
if (!(ipad || iphone || midp || uc7 || uc || android || windowsce || windowsmd)) {
// PC 端
}else{
// 移动端
}
}二、浏览器宽度区分 h# u1 P' i: p0 A9 X+ r# V6 ~+ ]
我们可以利用js代码,来判断访问者设备屏幕的宽度的大小来确定访客的设备是否为移动设备。
, ?; F: L6 j" _6 I2 E3 e window.screen.availWidth:用来获取浏览器屏幕的宽度。
5 p7 b1 F8 A5 ~, v5 X3 T window.screen.availHeight:用来获取浏览器屏幕的高度。 <script>
if(window.screen.availWidth<768){
//移动端
}else{
//PC端
}
</script>三、js判断是否ios或Android
& V; N9 `$ F% i; p; D7 a0 q, J' I. [ var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端 区分Android、iphone、ipad:
. ?! l5 Q5 |$ y8 }' a' ^* N ar ua = navigator.userAgent.toLowerCase();
if (/android|adr/gi.test(ua)) {
// 安卓
} else if (/\(i[^;]+;( U;)? CPU.+Mac OS X/gi.test(ua)) {
//苹果
} else if (/iPad/gi.test(ua)) {
//ipad
}四、js区分判断访客的浏览器
, V3 Y/ t- ? e var ua = navigator.userAgent.toLowerCase();
if (/msie/i.test(ua) && !/opera/.test(ua)) {
alert("IE");
return;
} else if (/firefox/i.test(ua)) {
alert("Firefox");
return;
} else if (/chrome/i.test(ua) && /webkit/i.test(ua) && /mozilla/i.test(ua)) {
alert("Chrome");
return;
} else if (/opera/i.test(ua)) {
alert("Opera");
return;
} else if (/iPad/i) {
alert("ipad");
return;
}
if (/webkit/i.test(ua) && !(/chrome/i.test(ua) && /webkit/i.test(ua) && /mozilla/i.test(ua))) {
alert("Safari");
return;
} else {
alert("unKnow");
}