js根据手机屏幕控制像素

常见的手机屏幕的分辨率各种各样,根据手机屏幕控制像素实现屏幕自适应。

<script>
    (function () {
        var standardDpi, dpi, w, scale, text;
        w = window.screen.width;
        if (w > 0) {
            if (w < 320) {
                standardDpi = 120;
            } else if (w < 480) {
                standardDpi = 160;
            } else if (w < 640) {
                standardDpi = 240;
            } else if (w < 960) {
                standardDpi = 320;
            } else if (w < 1280) {
                standardDpi = 480;
            } else {
                standardDpi = 640;
            }
        }
        dpi = 640 * standardDpi / w;
        dpi = Math.floor(dpi);
        scale = 640 / w;
        var userAgt=navigator.userAgent;
        if(window.devicePixelRatio === 3 && window.navigator.appVersion.match(/iphone/gi)){
            // iphone6 plus
            text = '<meta name="viewport" content="width=device-width, initial-scale=0.64, maximum-scale=0.64, minimum-scale=0.64, user-scalable=no" />';
        }else if (window.devicePixelRatio === 2 && window.navigator.appVersion.match(/iphone/gi)) {
            text = '<meta name="viewport" content="width=device-width, initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no" />';
        }else if(userAgt.match(/Firefox/gi)||(userAgt.match(/Chrome/gi) && !userAgt.match(/MicroMessenger/gi))) {
            text = '<meta name="viewport" content="width=640,initial-scale='+ (w / 640) +', maximum-scale='+ (w / 640) +', minimum-scale='+ (w / 640) +', user-scalable=no"/>';
        } else{
            text = '<meta name="viewport" content="width=640,initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0,target-densitydpi=' + dpi + ', user-scalable=no"/>';
        }
        document.write(text);
        if ("-ms-user-select" in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/)) {
            var msViewportStyle = document.createElement("style");
            msViewportStyle.appendChild(
                document.createTextNode("@-ms-viewport{width:auto!important}")
            );
            document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
        }
    })();
</script>

转载于:https://www.cnblogs.com/sam976/p/5762282.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值