如何判断用户设备类型

当我们在访问手机端的页面时想跳转到pc端做判断的代码

 1 <!DOCTYPE html>
 2 <html>
 3 
 4 <head>
 5     <title></title>
 6     <script type="text/javascript" charset="utf-8" async defer>
 7   function IsPC() {
 8         var userAgentInfo = navigator.userAgent;
 9         var Agents = ["Android", "iPhone",
10             "SymbianOS", "Windows Phone",
11             "iPad", "iPod"
12         ];
13         var flag = true;
14         for (var v = 0; v < Agents.length; v++) {
15             if (userAgentInfo.indexOf(Agents[v]) > 0) {
16                 flag = false;
17                 break;
18             }
19         }
20         return flag;
21     }
22 
23     function browserRedirect() {
24         var flag = IsPC(); //true为PC端,false为手机端
25         if (flag == true) {
26             alert('pc');
27         } else {
28             var res = confirm('是否跳转到pc');
29             if (res) {
30                 window.location.href = "http://www.baidu.com";
31             }
32         }
33     }
34 
35     (function() {
36         var flag = IsPC(); //true为PC端,false为手机端
37         if (flag == true) {
38             window.location.href = "http://www.aliyun.com";
39         }
40     })();
41     </script>
42 </head>
43 
44 <body>
45     <a onclick="browserRedirect()">跳转到电脑版</a>
46 </body>
47 
48 </html>

当页面加载时自动判断用户的设备类型,方法一可以改上面的方法也行,只不过改成自调用函数就行了,下面介绍介绍一下另外一种方法

<!DOCTYPE html>
<html>

<head>
    <title></title>
    <script type="text/javascript" charset="utf-8" async defer>
         function IsPC() {
           if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {
               alert('mb');
           }
        }
        IsPC();
    </script>
</head>

<body>
</body>

</html>

借鉴网上的代码

<script language="javascript">
function is_mobile() {
    var regex_match = /(nokia|iphone|android|motorola|^mot-|softbank|foma|docomo|kddi|up.browser|up.link|htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte-|longcos|pantech|gionee|^sie-|portalmmm|jigs browser|hiptop|^benq|haier|^lct|operas*mobi|opera*mini|320x320|240x320|176x220)/i;
  var u = navigator.userAgent;
  if (null == u) {
   return true;
  }
  var result = regex_match.exec(u);

  if (null == result) {
   return false
  } else {
   return true
  }
 }
 if (is_mobile()) {
    if (confirm('是否跳转到pc')) {
        document.location.href= '/wap';
    }
  
 }
</script>

  

posted @ 2017-01-08 02:03  7small7  阅读(286)  评论(0编辑  收藏  举报