想要实现的效果 最小为1920屏幕,大于1920的 扩大
npm i postcss-pxtorem -D
新建.postcssrc.js文件
module.exports = {
plugins: {
autoprefixer: {},
"postcss-pxtorem": {
"rootValue": 14,
"propList": ["*"],
minPixelValue: 2, // (Number) 设置要替换的最小像素值.
}
}
}
新建rem.js文件
const baseSize = 14;
// 设置 rem 函数
function setRem() {
// 当前页面宽度相对于 1920宽的缩放比例,可根据自己需要修改。
let docEle = document.documentElement;
const scale = docEle.clientWidth / 1920;
// 设置页面根节点字体大小(“Math.min(scale, 5)” 指最高放大比例为5,可根据实际业务需求调整)
let scalSize = baseSize * Math.min(scale, 5);
if (scalSize > baseSize) {
docEle.style.fontSize = `${scalSize.toFixed(2)}px`;
} else {
docEle.style.fontSize = `${baseSize}px`;
}
}
// 初始化
setRem();
// 改变窗口大小时重新设置 `rem` 加上防抖
let timeout;
window.onresize = function () {
clearTimeout(timeout);
timeout = setTimeout(setRem(), 100);
};
main.js中引入rem文件
import '@/libs/rem.js';
结束~~