学无先后,达者为师

网站首页 Vue 正文

vue vue-cli rem适配 手写rem

作者:陌雄 更新时间: 2022-01-14 Vue

1.安装依赖

npm install amfe-flexible -S
npm install postcss-px2rem -S

2.引入lib-flexible

// 在入口main.js中 引入 lib-flexible
import "amfe-flexible/index.js";

3.配置post-px2rem

postcss-pxtorem 在vue.config.js中配置

module.exports = {
   css: {
       loaderOptions: {
         css: {},
         postcss: {
       plugins: [
         require("postcss-px2rem")({
           remUnit: 75
         })
       ]
     }
       }
   }
}

4.使用方法

按照上面的步骤写完后,使用时设计图750px的,那设计图要是300px的宽度,那代码里面写成300px。这样就可以了

5.不匹配(不想将px变为rem)

.nav {
  width: 400px;
  height: 300px;
  background: red;
  border: 1px solid black; /*no*/
}

6.手写rem适配

<script>
	// 封装一个根据屏幕尺寸自动改变html的font-size大小的函数
function rem() {
    //  获取html的宽度
    let htmlW = document.documentElement.clientWidth;
    // 获取body的宽度
    let bodyW = document.body.clientWidth;
    // 兼容处理
    let W = htmlW || bodyW;
    // 设置html的font-size大小
    // 因为设计图尺寸是750,所以平分,这样*100之后,1rem就等于100px;
    document.documentElement.style.fontSize = (W / 750 * 100) + 'px';
  }
  // 定义屏幕宽度改变时触发
  window.onresize = function () {
    rem()
  }
  // 设置初始触发一次
rem()
	</script>

原文链接:https://blog.csdn.net/qq2877885856/article/details/122252903

栏目分类
最近更新