一、实现思路
! S$ @% \3 e- {: I4 J 可以通过 JavaScript 来实现判断当前的设备类型:navigator 是 JavaScript 中的一个独立的对象,用于提供用户所使用的浏览器以及操作系统等信息,以 navigator 对象属性的形式来提供。所有浏览器都支持该对象。# G: d4 {- C! _5 x. q |* u5 N6 R
而 navigator 对象有一个 userAgent 属性,会返回用户的设备操作系统和浏览器的信息。 此时可以通过 userAgent 判断是 H5 浏览器还是 PC 浏览器。而 App 不能获取 Window 的浏览器对象 navigator 的。那么可以在之前判断是否存在 navigator,不存在即为 App。
- U& Y7 \- w# } function fIsMobile(){
return /Android|iPhone|iPad|iPod|BlackBerry|webOS|Windows Phone|SymbianOS|IEMobile|Opera Mini/i.test(navigator.userAgent);
} 或者:
. U$ N1 w4 S+ F0 u/ ~! E 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{
// 移动端
}
}二、浏览器宽度区分 / M+ P6 W& i, z: n4 ~& x
我们可以利用js代码,来判断访问者设备屏幕的宽度的大小来确定访客的设备是否为移动设备。
4 c0 Y1 v4 L' f4 p9 f window.screen.availWidth:用来获取浏览器屏幕的宽度。1 V+ ^! E$ ~7 h2 p3 g
window.screen.availHeight:用来获取浏览器屏幕的高度。 <script>
if(window.screen.availWidth<768){
//移动端
}else{
//PC端
}
</script>三、js判断是否ios或Android . e! b' A# I4 ~! T1 n
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:0 H9 S) }, G: |4 g/ [
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区分判断访客的浏览器
$ Z# u( F3 O6 W: E% O w 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");
}