直接上代码
rem.js
import _ from 'lodash';
import Vuex from './store/index';
// 以1920px 底图为准开发页面
const setNowSize = () => {
const height = window.innerHeight;
const width = window.innerWidth;
Vuex.commit('updateWindowSize', JSON.stringify({ height, width }));
return { height, width };
};
// 需要在main.js执行一次
export const setDomFontSize = () => {
const { height: heightD, width: widthD } = setNowSize();
let width = document.documentElement.clientWidth || document.body.clientWidth;
let fontsize = (width <= 1200 ? 1200 : width) / 100 + 'px';
if (widthD >= 2880 && heightD < 1620) {
fontsize = (width <= 1200 ? 1200 : width / 2) / 100 + 'px';
}
document.getElementsByTagName('html')[0].style['font-size'] = fontsize;
};
let setDomFontSizeDebounce = _.debounce(setDomFontSize, 400);
window.addEventListener('resize', setDomFontSizeDebounce); // 浏览器加入收缩监听防抖,重新计算rem配置
vscode用户推荐安装插件: px to rem
postcss.config.js
代码不用写rem,使用postcss-plugin-px2rem将代码中的px转为rem
新建postcss.config.js
module.exports = {
plugins: [
require('autoprefixer'), // 自动添加前缀
require('postcss-rtlcss').postcssRTLCSS(), // rtl布局
require('postcss-plugin-px2rem')({
rootValue: 19.2, // 换算基数,1rem相当于10px,值为37.5时,1rem为20px,淘宝的flex默认为1rem为10px
// unitPrecision: 5, //允许REM单位增长到的十进制数字。
//propWhiteList: [], //默认值是一个空数组,这意味着禁用白名单并启用所有属性。
propBlackList: ['border'], //忽略自适应属性黑名单
exclude: false, //默认false,可以(reg)利用正则表达式排除某些文件夹的方法,例如/(node_module)\/如果想把前端UI框架内的px也转换成rem,请把此属性设为默认值
selectorBlackList: ['html', 'body', '#app'], //要忽略并保留为px的选择器
// ignoreIdentifier: false, //(boolean/string)忽略单个属性的方法,启用ignoreidentifier后,replace将自动设置为true。
// replace: true, // (布尔值)替换包含REM的规则,而不是添加回退。
mediaQuery: false, //(布尔值)允许在媒体查询中转换px。
minPixelValue: 3, //设置要替换的最小像素值(3px会被转rem)。 默认 0
}),
],
};
配合起来使用,直接写px 就会实现页面大小的适配