移动端Vue项目屏幕自适应解决方案:详解rem的运用方法
最编程
2024-02-12 07:11:07
...
// 设置全局rem 函数
function setRem() {
// 1, 获取窗体宽度
let htmlWidth =
document.documentElement.clientWidth || document.body.clientWidth;
// 2, 根据宽度计算出合适的根字体大小
let rootFontSize = htmlWidth / 26.7 || 12;
// 3, 判断多种情况,根字体大小做相应的调整
if (htmlWidth < 375) {
rootFontSize = 11;
} else if (375 <= htmlWidth < 414) {
rootFontSize = 12;
} else {
rootFontSize = 13;
}
//4, js设置根字体为rootFontSize的大小
let htmlDom = document.getElementsByTagName("html")[0];
htmlDom.style.fontSize = rootFontSize + "px";
}
setRem();
// 窗口size变动的时候调用setRem函数
Window.onresize = function() {
setRem();
};
具体使用:
1,在utils目录下新建rem.js文件,把以上代码复制进去
2,在main.js文件引入:
// 引入rem, 设置根字体大小
import "./utils/rem";