Vue中750设计稿px自动转化成rem

一、下载 postcss-pxtorem

运行 npm install postcss-pxtorem
完成下载之后,在package.json文件中添加这段代码

"postcss": { // 新添加的
  "plugins": {
    "autoprefixer": {},
    "postcss-pxtorem": {
      "rootValue": 37.5, 
      "propList": [
      "*"
      ]
    }
  }
},
"browserslist": [ // 之前就有的,作为位置参照放在这里
  "> 1%",
  "last 2 versions",
  "not ie <= 8"
]

二、在项目utils文件夹,创建rem.js文件

添加下列代码

function setRem() {
	let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth
	let htmlDom = document.querySelector('html')
	htmlDom.style.fontSize = htmlWidth / 20 + 'px'
}
setRem();
window.onresize = function () {
	setRem()
}

三、在main.js中引入

import './utils/rem.js'

移动端H5页面在PC端固定视图大小

  • clientWidth:浏览器窗口文档显示的宽度。
  • offsetWidth:根节点html元素对象的宽度。

把clientWidth改成offsetWidth。
然后找到vue项目中的public文件夹里面的index.html,在这个文件中把html标签后面添加 style='max-width:750px ; margin: 0 auto'
这样之后在PC端无论浏览器宽度有多大,它只会最大显示宽度为750px宽度时候的自适应样式。

おすすめ

転載: blog.csdn.net/xiamoziqian/article/details/108886076