欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

移动端页面适配

程序员文章站 2022-06-21 10:47:05
...

用rem代替px和em

(function(window, document) {
    'use strict';
    //设置rem
    var remcss = {}; 
    (function() {
        var viewportEl = document.querySelector('meta[name="viewport"]'),
        dpr = window.devicePixelRatio || 1,
        maxWidth = 750,
        designWidth = 750,
        content = 'width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no';
        dpr = dpr >= 3 ? 3 : (dpr >= 2 ? 2 : 1);
        remcss.dpr = dpr;
        remcss.maxWidth = maxWidth;
        remcss.designWidth = designWidth;
        remcss.content = content;
        document.documentElement.setAttribute('data-dpr', dpr);
        document.documentElement.setAttribute('max-width', maxWidth);
        if (designWidth) {
            document.documentElement.setAttribute('design-width', designWidth);
            remcss.designWidth = designWidth
        }
        if (viewportEl) {
            viewportEl.setAttribute('content', remcss.content)
        } else {
            viewportEl = document.createElement('meta');
            viewportEl.setAttribute('name', 'viewport');
            viewportEl.setAttribute('content', remcss.content);
            document.head.appendChild(viewportEl)
        }
    })();
    remcss.setFontsize = function() {
        var innerWidth = document.documentElement.getBoundingClientRect().width || window.innerWidth;
        if (remcss.maxWidth && (innerWidth / remcss.dpr > remcss.maxWidth)) {
            innerWidth = remcss.maxWidth * remcss.dpr
        }
        if (!innerWidth) {
            return false
        }
        document.documentElement.style.fontSize = (innerWidth * 100 / remcss.designWidth) + 'px';
        remcss.callback && remcss.callback()
    };
    remcss.setFontsize();
    window.addEventListener('resize',
    function() {
        clearTimeout(remcss.restime);
        remcss.restime = setTimeout(remcss.setFontsize, 100)
    },
    false);
    window.addEventListener('DOMContentLoaded', remcss.setFontsize, false);
    window.remcss = remcss;

    //判断是竖向还是横向
    var initOrientation = function () {
        var updateOrientation = function () {
            var orientation = window.orientation;
            switch (orientation) {
                case 90:
                case -90:
                    orientation = 'landscape';
                    break;
                default:
                    orientation = 'portrait';
                    break;
            }
            document.body.parentNode.setAttribute('class', orientation);
        };
        window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", updateOrientation, false);
        updateOrientation();
    };
    window.addEventListener('DOMContentLoaded', initOrientation, false);
})(window, document);

注意

maxWidth为页面最大宽度

designWidth为设计稿宽度,根据自身设计稿去配置即可

上面配置1rem=100px,就是设计稿里面的100px