凌晨不睡觉

V1

2022/10/31阅读:25主题:默认主题

通过分辨率区分iPhone型号(更新至13系列)

最近几代的iPhone基本换壳分辨率差异不大,所以暂时不更新了。

前言

通常分辨访问的设备型号基本都是读取userAgent解析即可,但是iOS的userAgent并不会包含手机型号,所以只能另辟蹊径了。

原理

读取到设备类型为iOS后就去读取设备的分辨率,然后与每一代iPhone的标准对比就可以得出一个大致的设备型号,虽然不精准但也足够了。 通过获取设备逻辑像素宽高(window.screen.widthwindow.screen.height)与DPR(window.devicePixelRatio)这三要素然后依据如下图进行判断(数据已查阅多方资料核对)。 在这里插入图片描述

核心代码

          function iPhoneModel({
            var isIphone = /iphone/gi.test(navigator.userAgent);
            if (isIphone) {
                var dpr = window.devicePixelRatio,
                    screenWidth = window.screen.width,
                    screenHeight = window.screen.height,
                    modelList = {
                        '320*480*1''2G/3G/3GS',
                        '320*480*2''4/4S',
                        '320*568*2''5/5S/5C/SE',
                        '375*667*2''6/6S/7/8/SE2',
                        '414*736*3''6Plus/6S Plus/7Plus/8Plus',
                        '375*812*3''X/XS/11 Pro',
                        '414*896*2''11/XR',
                        '414*896*3''XS_Max/11_Pro_Max',
                        '360*780*3''12_Mini/13_Mini',
                        '390*844*3''12/12_Pro/13/13_Pro',
                        '428*926*3''12_Pro_Max/13_Pro_Max'
                    }

                return modelList[screenWidth + '*' + screenHeight + '*' + dpr] || 'iPhone';
            } else {
                return false;
            }
        }

Demo

<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>判断iPhone型号</title>
</head>

<body>
    <script>
        function iPhoneModel({
            var isIphone = /iphone/gi.test(navigator.userAgent);
            if (isIphone) {
                var dpr = window.devicePixelRatio,
                    screenWidth = window.screen.width,
                    screenHeight = window.screen.height,
                    modelList = {
                        '320*480*1''2G/3G/3GS',
                        '320*480*2''4/4S',
                        '320*568*2''5/5S/5C/SE',
                        '375*667*2''6/6S/7/8/SE2',
                        '414*736*3''6Plus/6S Plus/7Plus/8Plus',
                        '375*812*3''X/XS/11 Pro',
                        '414*896*2''11/XR',
                        '414*896*3''XS_Max/11_Pro_Max',
                        '360*780*3''12_Mini/13_Mini',
                        '390*844*3''12/12_Pro/13/13_Pro',
                        '428*926*3''12_Pro_Max/13_Pro_Max'
                    }

                return modelList[screenWidth + '*' + screenHeight + '*' + dpr] || 'iPhone';
            } else {
                return false;
            }
        }
        document.write(iPhoneModel())
    
</script>
</body>

</html>

分类:

前端

标签:

JavaScript

作者介绍

凌晨不睡觉
V1