1、安装 postcss-pxtorem
1 |
npm install postcss postcss-pxtorem --save-dev |
2、在根目录新建postcss.config.js,配置 postcss-pxtorem
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
module.exports = { plugins: { // autoprefixer: {}, 'postcss-pxtorem': { // rootValue: 75, // 设计稿宽度的1/10 rootValue({ file }) { // 判断是否是vant的文件 如果是就使用 37.5为根节点字体大小 // 否则使用75 因为vant使用的设计标准为375 但是市场现在的主流设置尺寸是750 return file.indexOf('vant') !== -1 ? 37.5 : 75; }, unitPrecision: 5, // 保留rem小数点多少位 propList: ['*'], // 需要做转化处理的属性,如`hight`、`width`、`letter-spacing`等,`*`表示全部 // propBlackList: ['font-size'], //过滤掉不需要转换的属性 minPixelValue: 0, //px小于12的不会被转换,默认 0 selectorBlackList: [] // 忽略转换rem转换,正则匹配项(选择器),如:过滤点含有"el-"或以".ant"开头的选择器 // exclude: /(node_module)/ //默认false,可以(reg)利用正则表达式排除某些文件夹的方法,例如/(node_module)/ 。如果想把前端UI框架内的px也转换成rem,请把此属性设为默认值 } } }; |
注意:rootValue ,判断是否是vant的文件,如果是就使用 37.5为根节点字体大小;否则使用75,因为vant使用的设计标准为375,但是市场现在的主流设置尺寸是750
3、utils文件夹下,新建一个rem.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function setRem() { // 配置宽度为750px时,1rem的值为:75px; const screenWidth = 750; const scale = screenWidth / 75; const htmlWidth = document.documentElement.clientWidth || document.body.clientWidth; // 得到html的Dom元素 const htmlDom = document.getElementsByTagName('html')[0]; // 设置根元素字体大小 htmlDom.style.fontSize = htmlWidth / scale + 'px'; } // 初始化 setRem(); // 改变窗口大小时重新设置 rem window.onresize = function () { setRem(); }; |
4、main.js引入rem.js文件
1 |
import '@/utils/rem.js' |
5、但是postcss-px2rem插件并没有处理内联样式的功能,于是我们便需要对之自行处理。
1) 在src/utils/index.js下
1 2 3 4 5 6 7 8 |
export const px2rem = (px) => { if (/%/gi.test(px)) { // 有百分号%,特殊处理,表述pc是一个有百分号的数,比如:90% return px; } else { return parseFloat(px) / 75 + 'rem'; // 这里的75,和postcss.config.js里的rootValue值对应 } }; |
2)然后在main.js
1 2 |
import { px2rem } from '@/utils'; Vue.prototype.$px2rem = px2rem; |
3) 使用
1 |
<div :style="{ 'font-size': $px2rem('16px') }">测试</div> |