针对屏幕适配方案,当前存在px2rem-loader、postcss-pxtorem、postcss-px2rem以及postcss-plugin-px2rem,在当前使用过程中,由于是针对vue3和vite项目,目前测试postcss-pxtorem可以生效
1. 安装依赖
cnpm install postcss-pxtorem
cnpm install amfe-flexible
2. 在utils目录下新建文件rem.ts
// rem 函数
function setRem() {
const defalutWidth = 1920; // 默认宽度
const defalueScale = 1; // 默认比例关系
let defalutFontSize = 192; // 默认字体大小
const getWidth = window.innerWidth; // 获取屏幕的宽度
let currentScale = getWidth / defalutWidth; // 计算当前的屏幕大小和默认宽度之间的比例
// 防止缩放太小
if (currentScale < 0.85 && getWidth > 1024) {
currentScale = 0.855;
}
// 当前为平板时
if (getWidth <= 1024) {
defalutFontSize = defalutFontSize * 2;
}
// 计算的宽度比例关系 再 * 默认的字体大小,获取计算的字体大小
const currentFontSize = (currentScale / defalueScale) * defalutFontSize;
document.documentElement.style.fontSize = currentFontSize + "px";
}
// 调用方法
setRem();
// 监听窗口在变化时重新设置跟文件大小
window.onresize = function () {
setRem();
};
3. 将rem.ts文件以及amfe-flexible导入到main.ts中
import 'amfe-flexible'
import '@/utils/rem.ts'
4. 配置vite.config.ts
// 引入‘postcss-pxtorem’
import postCssPxToRem from 'postcss-pxtorem'
postcss: {
plugins: [
postCssPxToRem({
// 自适应,px>rem转换
rootValue: 192, //pc端建议:192,移动端建议:75;设计稿宽度的1 / 10
propList: ["*", "!border"], // 除 border 外所有px 转 rem // 需要转换的属性,这里选择全部都进行转换
selectorBlackList: [".norem"],
// 过滤掉norem-开头的class,不进行rem转换,这个内容可以不写
unitPrecision: 5, // 转换后的精度,即小数点位数
replace: true, // 是否直接更换属性值而不添加备份属性
mediaQuery: false, // 是否在媒体查询中也转换px为rem
minPixelValue: 0, // 设置要转换的最小像素值
}),
],
},