美文网首页
如何在vue的web页面中像小程序中使用rpx单位做兼容

如何在vue的web页面中像小程序中使用rpx单位做兼容

作者: zhyzhyzz | 来源:发表于2020-03-24 14:47 被阅读0次

    该功能基于vue-cli3;cli2的方法大差不差

    准备工作:

    1、postcss-px2rem-exclude(推荐) || postcss-px2rem(不推荐);
    2、rem.js
    
    第一步:
    npm install postcss-px2rem-exclude --save
    
    //找到:postcss.config.js
    //在plugins新增
    'postcss-px2rem-exclude': {
          remUnit: 37.5,//结果为:设计稿元素尺寸/16,比如元素宽320px,最终页面会换算成 20rem
          exclude: /node_modules|folder_name/i     //屏蔽node_modules里的css,使用postcss-px2rem不能屏蔽,所以会导致引入的一些ui变形
       }
    
    第二步:
    新建rem.js
     // 设置 rem 函数
     function setRem() {
         // 320 默认大小16px; 320px = 20rem ;每个元素px基础上/16
         let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
         console.log(htmlWidth)
             //得到html的Dom元素
         let htmlDom = document.getElementsByTagName('html')[0];
         if (htmlWidth >= 450) {
             //设置根元素字体大小
             htmlDom.style.fontSize = 22 + 'px';
         } else {
             //设置根元素字体大小
             htmlDom.style.fontSize = htmlWidth / 20 + 'px';
         }
    
     }
     // 初始化
     setRem();
     // 改变窗口大小时重新设置 rem
     window.onresize = function() {
         setRem()
     }
    根据窗口大小动态设置根元素的size;
    

    以上两步就可以实现小程序中rpx功能,针对设计稿为750px的移动端。

    相关文章

      网友评论

          本文标题:如何在vue的web页面中像小程序中使用rpx单位做兼容

          本文链接:https://www.haomeiwen.com/subject/tkmoyhtx.html