方案解决问题:
动态根据UI稿移动端375px 适配最终比例大小
-
例如设计稿中375宽度下,宽度最优16px;那么在设备真实宽度375*1.2的比例下,UI元素宽度的最佳应该是16*1.2px
-
使用到的插件postcss-pxtorem做的事情是
– 先将16px作为插件参数设置根节点font-size为16px,– 插件会对配置中非白名单的文件进行px单位到rem单位的转换;
– 运行时,根据设备真实情况,动态设置根节点font-size,实现最终尺寸的适配
-
最后在window.resize时重新计算设置根节点font-size大小
步骤:
package.json所需loader版本
"postcss-loader": "^4.3.0",
"postcss-pxtorem": "^5.1.1",
vue.config.js
与devServer同级增加css.loaderOptions对象
devServer: {
//
},
css: {
loaderOptions: {
postcss: {
postcssOptions: {
plugins: [require('postcss-pxtorem')({
rootValue: 16, // 根字体大小
unitPrecision: 5,
propList : ['*'],
selectorBlackList : [],
replace: true,
mediaQuery: false,
minPixelValue: 0,
exclude: /node_modules/i
})]
}
}
}
},
chainWebpack: config => {},
// ...
main.js主入口文件
import remSize from './remSize.js';
remSize();
window.addEventListener('resize', () => {
remSize();
})
remSize.js文件
// 设备判断
export default function remSize(noRest) {
let winWidth;
// 获取窗口宽度
if (window.innerWidth) {
winWidth = window.innerWidth;
} else if ((document.body) && (document.body.clientWidth)) {
winWidth = document.body.clientWidth;
}
// 通过深入Document内部对body进行检测,获取窗口大小
if (
document.documentElement
&& document.documentElement.clientHeight
&& document.documentElement.clientWidth
) {
winWidth = document.documentElement.clientWidth;
}
// 修改font-size
const fontSize = ((winWidth / 375) * 16).toFixed(4); // 🚨🚨🚨375设计稿宽度,16同css.loaderOptions.postcss.postcssOptions.plugins中postcss-pxtorem插件的配置项rootValue值
document.documentElement.style.fontSize = `${fontSize}px`;
console.log(fontSize, 'setResize');
// 适配对font-size额外处理的手机
const nowFontSize = parseFloat(getComputedStyle(document.documentElement, false)['font-size']).toFixed(4);
if (noRest !== true && `${nowFontSize}` !== fontSize) {
document.documentElement.style.fontSize = `${(fontSize * fontSize) / nowFontSize}px`;
}
}