在vue项目中使用postcss-px2rem插件把px转变为rem,并配合给html根元素设置fontsize,来实现页面的自适应效果
- 安装postcss-px2rem插件,目的:把px转变为rem
- vue.config.js中配置remUnit
- 通过js改变html的fontsize值
- postcss-px2rem插件不能把行内样式进行pxTorem的转换
安装postcss-px2rem插件,目的:把px转变为rem
| npm install postcss-px2rem -S |
| |
复制
vue.config.js中配置remUnit
| const port = process.env.port || 8081 // 端口 |
| module.exports = { |
| devServer: { |
| host: '0.0.0.0', |
| port: port, |
| open: true, |
| }, |
| css: { |
| loaderOptions: { |
| css: {}, |
| postcss: { |
| plugins: [ |
| require('postcss-px2rem')({ |
| remUnit: 100 |
| }) |
| ] |
| } |
| } |
| } |
| } |
复制
| 一直不太明白为什么remUnit设置为100,通过项目中不断的改变remUnit值, |
| |
| 发现这里remUnit值是为了把px转换成rem的计算值, |
| |
| 即remUnit=100, |
| |
| 则1rem=100px,1px=0.01rem |
| |
| 当项目中我们在css样式中设置width:750px时,经过[postcss-px2rem]这个插件转换 |
| remStyle:转换后的值(单位:rem) |
| |
| pxStyle:转换前的值(单位:px) |
| |
| remStyle=(pxStyle/remUnit)+'rem' |
| |
| 得到:width:7.5rem |
复制
通过js改变html的fontsize值
| <script type="text/javascript"> |
| function getHtmlFontSize() { |
| |
| let deviceWidth = document.documentElement.clientWidth || window.innerWidth; |
| console.log("[设备宽度]", deviceWidth); |
| if (deviceWidth >= 750) { |
| deviceWidth = 750; |
| } else if (deviceWidth <= 320) { |
| deviceWidth = 320; |
| } |
| |
| document.documentElement.style.fontSize = (deviceWidth / 7.5) + 'px'; |
| } |
| getHtmlFontSize(); |
| window.addEventListener("resize", getHtmlFontSize) |
| </script> |
复制
postcss-px2rem插件不能把行内样式进行pxTorem的转换