移动端自适应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%,百分比布局

  px转vw

  https://developer.aliyun.com/mirror/npm/package/postcss-px-to-viewport

npm install postcss-px-to-viewport --save-dev
// postcss.config.js
module.exports = {
  plugins: {
    autoprefixer: {},
    'postcss-px-to-viewport': {
      viewportWidth: 375, // 视窗的宽度,对应的是我们设计稿的宽度,一般是750
      // viewportHeight: 1334, // 视窗的高度,根据750设备的宽度来指定,一般指定1334,也可以不配置
      unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数(很多时候无法整除)
      viewportUnit: 'vw', // 指定需要转换成的视窗单位,建议使用vw
      selectorBlackList: ['.ignore', '.hairlines'], // 指定不转换为视窗单位的类,可以自定义,可以无限添加,建议定义一至两个通用的类名
      minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位,你也可以设置为你想要的值
      mediaQuery: false // 允许在媒体查询中转换`px`
    },
    'postcss-viewport-units': {
      // 排除会产生警告的部份
      filterRule: rule => rule.nodes.findIndex(i => i.prop === 'content') === -1
    },
    cssnano: {
      preset: 'advanced',
      autoprefixer: false, // 和autoprefixer同样具有autoprefixer,保留一个
      'postcss-zindex': false
    }
  }
}

二、rem

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

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

三、rem配置(方式1)

  px自动转换rem,postcss-pxtorem

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

npm install postcss-pxtorem -D

   自动转换设置(vue-cli3)

// postcss.config.js
module.exports = {
  plugins: {
    autoprefixer: {},
    'autoprefixer': {
      browsers: ['Android >= 4.0', 'iOS >= 7']
    },
    'postcss-pxtorem': {
      rootValue: 10,// 转换1rem=10px
      propList: ['*']
    }
  }
}

四、rem配置(方式2)

  更多详情可参考:https://my.oschina.net/parchments/blog/1794335

  1. lib-flexible,手淘开发,用于适配移动端的开源库

  安装lib-flexible

    github:https://github.com/amfe/lib-flexible

npm install lib-flexible --save-dev
npm install px2rem-loader --save-dev

  

  2. 引入(vue)

// main.js
import 'lib-flexible'

  

  3. 配置(vue-cli3.0)

// vue.config.js
module.exports = {
    css: {
        loaderOptions: {
            css: {},
            postcss: {
                plugins: [
                    require('postcss-px2rem')({
                        // 以设计稿750为例, 750 / 10 = 75
                        remUnit: 75
                    }),
                ]
            }
        }
    },
};

  4. 修改最大适配尺寸

  依赖包中打开./node_modules/lib-flexible/flexible.js

// ./node_modules/lib-flexible/flexible.js 
// 找到该方法,默认最大适配尺寸为540px,修改540为需要值,重新运行项目即可
   function refreshRem(){
        var width = docEl.getBoundingClientRect().width;
        if (width / dpr > 540) {
            width = 540 * dpr;
        }
        var rem = width / 10;
        docEl.style.fontSize = rem + 'px';
        flexible.rem = win.rem = rem;
    }

 五、rem配置(方式3)rem.js

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

   两个参数分别是designWidth 和maxWidth,顾名思义,就是我们设计稿的宽度和我们设定的最大宽度

   main.js中引入rem.js(vue)

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

    function refreshRem() {
        var width = docEl.getBoundingClientRect().width;
        console.log(width,"width",maxWidth,"maxWidth")
        if (!maxWidth) {
            maxWidth = 540;
        }
        ;
        if (width > maxWidth) {
            width = maxWidth;
        }
        //与淘宝做法不同,直接采用简单的rem换算方法1rem=10px,与上面rootValue应该保持一致
        var rem = width * 10 / 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 = "32px";
    // } else {
    //     doc.addEventListener("DOMContentLoaded", function (e) {
    //         doc.body.style.fontSize = "32px";
    //     }, false);
    // }
})(375, 750);
原文地址:https://www.cnblogs.com/jing-zhe/p/12781276.html