js 判断用户设备类型及平台

警告
本文最后更新于 2023-07-07,文中内容可能已过时。

前端开发经常遇到需要判断用户的浏览设备,是 pc 端还是移动端,移动端使用的是什么手机系统?android、ios、ipad、windows phone 等等,有时候还需要知道用户浏览页面是在微信中打开还是在移动端浏览器中打开,等等一系列判断做一些相应的处理。

首先判断 pc 端还是移动端

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function IsPC() {
        var userAgentInfo = navigator.userAgent;
        var Agents = ["Android", "iPhone",
                    "SymbianOS", "Windows Phone",
                    "iPad", "iPod"];
        var flag = true;
        for (var v = 0; v < Agents.length; v++) {
            if (userAgentInfo.indexOf(Agents[v]) > 0) {
                flag = false;
                break;
            }
        }
        return flag;
    }

判断用户移动端使用的系统平台

1
2
3
4
5
6
7
8
var u = navigator.userAgent;
    if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
        //安卓手机
    } else if (u.indexOf('iPhone') > -1) {
        //苹果手机
    } else if (u.indexOf('Windows Phone') > -1) {
        //winphone 手机
    }

判断用户是否在微信中打开

1
2
3
4
5
6
7
8
function isWeiXin(){
        var ua = navigator.userAgent.toLowerCase();
        if(ua.indexOf('micromessenger') != -1) {
            return true;
        } else {
            return false;
        }
    }

实际运用

根据 pc 或者移动端控制飘花数目,降低 cpu 消耗,减少卡顿。demo

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  <script>
    function sakuraInit() {
        $(document).snowfall('clear');
        var userAgentInfo = navigator.userAgent;
        var Agents = ["Android", "iPhone",
                    "SymbianOS", "Windows Phone",
                    "iPad", "iPod"];
        var flag = true;
        for (var v = 0; v < Agents.length; v++) {
            if (userAgentInfo.indexOf(Agents[v]) > 0) {
                flag = false;
                break;
            }
        }
        if (flag) {
            $(document).snowfall({image:"images/1.png", flakeCount:5, minSpeed:1, minSize:8, maxSize:15,});
            $(document).snowfall({image:"images/2.png", flakeCount:5, minSpeed:1, minSize:8, maxSize:15,});
            $(document).snowfall({image:"images/3.png", flakeCount:5, minSpeed:1, minSize:8, maxSize:15,});
            $(document).snowfall({image:"images/4.png", flakeCount:5, minSpeed:1, minSize:8, maxSize:15,});
        } else {
            $(document).snowfall({image:"images/1.png", flakeCount:2, minSpeed:1, minSize:8, maxSize:15,});
            $(document).snowfall({image:"images/2.png", flakeCount:2, minSpeed:1, minSize:8, maxSize:15,});
            $(document).snowfall({image:"images/3.png", flakeCount:2, minSpeed:1, minSize:8, maxSize:15,});
            $(document).snowfall({image:"images/4.png", flakeCount:2, minSpeed:1, minSize:8, maxSize:15,});
        }
    }
    window.onload = sakuraInit();
  </script>
Buy me a coffee~
支付宝
微信
0%