vue.config.js中使用postcss-pxtorem

文章介绍了如何利用postcss-pxtorem插件和CSSloaderOptions进行移动端适配。通过设置根节点font-size并根据设备真实宽度动态调整,确保UI元素在不同设备上按比例显示。在Vue.js项目中,主入口文件和remSize.js协同工作,监听窗口大小变化,实时更新font-size,以实现响应式布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方案解决问题:

动态根据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`;
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值