移动端布局vw+vh+rem

vw+vh+rem

一、vw、vh

  vw、vh是基于视口的布局方案,故这个meta元素的视口必须声明。(视口宽度等于设备宽度,初始不缩放,用于解决页面宽高自动适配屏幕)

 <meta name="viewport" content="width=device-width,initial-scale=1.0">

  1vw等于设备宽度的1%,同理1vh等于设备高度的1%,百分比布局

  无其他配置,直接使用

二、rem

  相对单位,根据CSS的媒体查询功能,更改html根字体大小,实现字体大小随屏幕尺寸变化。

  举例:浏览器默认html的字体大小为16px,则1rem=16px

扫描二维码关注公众号,回复: 11131499 查看本文章

三、px自动转换rem,postcss-pxtorem

  github:https://github.com/cuth/postcss-pxtorem

npm install postcss-pxtorem -D

四、配置rem

  创建rem.js,main.js引入(vue)

  参考:https://www.jianshu.com/p/98ab31ed7018

(function (designWidth, maxWidth) {
    var doc = document,
        win = window;
    var docEl = doc.documentElement;
    var tid;
    var rootItem, rootStyle;

    function refreshRem() {
        var width = docEl.getBoundingClientRect().width;
        if (!maxWidth) {
            maxWidth = 540;
        }
        ;
        if (width > maxWidth) {
            width = maxWidth;
        }
        //与淘宝做法不同,直接采用简单的rem换算方法1rem=100px
        var rem = width * 100 / designWidth;
        //兼容UC开始
        rootStyle = "html{font-size:" + rem + 'px !important}';
        rootItem = document.getElementById('rootsize') || document.createElement("style");
        if (!document.getElementById('rootsize')) {
            document.getElementsByTagName("head")[0].appendChild(rootItem);
            rootItem.id = 'rootsize';
        }
        if (rootItem.styleSheet) {
            rootItem.styleSheet.disabled || (rootItem.styleSheet.cssText = rootStyle)
        } else {
            try {
                rootItem.innerHTML = rootStyle
            } catch (f) {
                rootItem.innerText = rootStyle
            }
        }
        //兼容UC结束
        docEl.style.fontSize = rem + "px";
    };
    refreshRem();

    win.addEventListener("resize", function () {
        clearTimeout(tid); //防止执行两次
        tid = setTimeout(refreshRem, 300);
    }, false);

    win.addEventListener("pageshow", function (e) {
        if (e.persisted) { // 浏览器后退的时候重新计算
            clearTimeout(tid);
            tid = setTimeout(refreshRem, 300);
        }
    }, false);

    if (doc.readyState === "complete") {
        doc.body.style.fontSize = "16px";
    } else {
        doc.addEventListener("DOMContentLoaded", function (e) {
            doc.body.style.fontSize = "16px";
        }, false);
    }
})(375, 750);

猜你喜欢

转载自www.cnblogs.com/jing-zhe/p/12781276.html