一、下载插件适配rem
第一步:先安装依赖
npm install amfe-flexible -S
npm install postcss-px2rem -S
第二步: 引入lib-flexible
// 在入口main.js中 引入 lib-flexible
import "amfe-flexible/index.js";
注意事项(important): 由于flexible会动态给页面header中添加标签,所以务必请把目录 public/index.html 中的这个标签删除!!!
第三步: 配置post-px2rem
新建postcss-pxtorem 或者在postcss.config.js中都能配置
module.exports = {
css: {
loaderOptions: {
css: {},
postcss: {
plugins: [
require("postcss-px2rem")({
remUnit: 75
})
]
}
}
}
}
第四步:使用方法
按照上面的步骤写完后,使用时设计图750px的,那设计图要是300px的宽度,那代码里面写成300px。这样就可以了
二、手写rem
<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>