怎么在移动端的vue项目中进行屏幕适配(rem布局)

1.首先创建一个rem.js文件,在main.js文件里面引入,具体配置如下

const baseSize = 32
// 设置 rem 函数
function setRem () {
// 当前页面宽度相对于 750 宽的缩放比例,可根据自己需要修改。
const scale = document.documentElement.clientWidth / 750
// 设置页面根节点字体大小
document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px' }
// 初始化
setRem()
// 改变窗口大小时重新设置 rem
window.onresize = function () {
setRem()
}

2.下载postcss-pxtorem (npm install postcss-pxtorem --save),具体配置如下
修改.postcssrc.js 文件,在里面添加配置项
"postcss-pxtorem": {
"rootValue": 32,
"propList": ["*"]
}
这样可以自动帮你把px转化为rem,方便一点,如果想在项目中直接写rem单位的话,可以在index.html里面写如下配置: fnResize()
window.onresize = function () {
fnResize()
}
function fnResize() {
var deviceWidth = document.documentElement.clientWidth || window.innerWidth
if (deviceWidth >= 750) {
deviceWidth = 750
}
if (deviceWidth <= 320) {
deviceWidth = 320
}
document.documentElement.style.fontSize = (deviceWidth / 7.5) + 'px' }
此配置里面规定了100px = 1rem,在项目中可以直接使用rem单位,自己去算一下即可

转载于:https://juejin.im/post/5cf729c15188257480599434

猜你喜欢

转载自blog.csdn.net/weixin_33851604/article/details/91459936