学无先后,达者为师

网站首页 编程语言 正文

使用postcss插件配置rem和手写rem的方法

作者:洋养杨阳 更新时间: 2022-01-13 编程语言

一、下载postcss插件适配rem

1.0 安装依赖

在文件目录下cmd到黑窗户 运行以下代码

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

1.1 引入lib-flexible

// 在入口main.js中 引入 lib-flexible
import "amfe-flexible/index.js";
注意事项(important): 由于flexible会动态给页面header中添加标签,所以务必请把目录 public/index.html 中的这个标签删除!!!

1.2 PostCSS 配置

新建postcss-pxtorem 或者在postcss.config.js中都能配置

// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
  plugins: {
    autoprefixer: {
      overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 8']
    },
    'postcss-pxtorem': {
      rootValue: 37.5,
      propList: ['*']
    }
  }
}

1.3 使用方法

上面的步骤写完后,使用时设计图750px的,那设计图要是375px的宽度,那代码里面写成375px。因为vant中的宽度是双面屏,所以宽度需要减半。

二、 手写rem

style

<style>
    * {
      margin: 0;
      padding: 0;
    }
    .h {
      width: 7.5rem;
      height: 0.8rem;
      background-color: red;
    }
    .c {
      width: 7.5rem;
      background-color: orange;
      height: 5rem;
    }
    .f {
      width: 7.5rem;
      background-color: orchid;
      height: 0.5rem;
    }
  </style>

body


<body>
  <div class="h"></div>
  <div class="c"></div>
  <div class="f"></div>
</body>

script

<script>
	// 封装一个根据屏幕尺寸自动改变html的font-size大小的函数
function rem() {
    //  获取html的宽度
    let htmlW = document.documentElement.clientWidth; 
    // 获取body的宽度
    let bodyW = document.body.clientWidth;
    // IE10以下获取不到HTML的宽度    兼容处理
    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/weixin_58102387/article/details/122294200

栏目分类
最近更新