一、实现思路
3 l3 r8 `! @- P* h4 q 可以通过 JavaScript 来实现判断当前的设备类型:navigator 是 JavaScript 中的一个独立的对象,用于提供用户所使用的浏览器以及操作系统等信息,以 navigator 对象属性的形式来提供。所有浏览器都支持该对象。; Q; y. x- S3 o6 U+ n& `
而 navigator 对象有一个 userAgent 属性,会返回用户的设备操作系统和浏览器的信息。 此时可以通过 userAgent 判断是 H5 浏览器还是 PC 浏览器。而 App 不能获取 Window 的浏览器对象 navigator 的。那么可以在之前判断是否存在 navigator,不存在即为 App。
. I3 _5 X( A* D7 s
- function fIsMobile(){
- return /Android|iPhone|iPad|iPod|BlackBerry|webOS|Windows Phone|SymbianOS|IEMobile|Opera Mini/i.test(navigator.userAgent);
- }
或者: 5 \% y3 d" z- a9 F) z- c6 i9 Z
- 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{
- // 移动端
- }
- }
二、浏览器宽度区分
2 f1 \$ [0 g/ h6 o0 K% ~, ]. N 我们可以利用js代码,来判断访问者设备屏幕的宽度的大小来确定访客的设备是否为移动设备。
3 F0 @: L$ y7 ^1 R( U& d2 `window.screen.availWidth:用来获取浏览器屏幕的宽度。
* s! u I' ^) O+ ^3 Ywindow.screen.availHeight:用来获取浏览器屏幕的高度。 - <script>
- if(window.screen.availWidth<768){
- //移动端
- }else{
- //PC端
- }
- </script>
三、js判断是否ios或Android K& F( f" b& k, x1 w
- 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:
" w+ O* q: y7 f9 R' h- 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区分判断访客的浏览器* r6 ~+ w P3 n! g$ a, @' k. |
- 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");
- }
|