vue项目实现postcss-pxtoremvue大屏适配

1.安装依赖

npm install postcss-pxtorem autoprefixer postcss-loader --save-dev
# 或者
yarn add postcss-pxtorem autoprefixer postcss-loader --dev

2.配置 PostCSS

在项目根目录下创建一个 .postcssrc.js 文件,并添加以下配置:
module.exports = {
  plugins: {
    autoprefixer: {},
    'postcss-pxtorem': {
      rootValue: 16, // 1rem = 16px
      propList: ['*'], // 转换所有属性
      unitPrecision: 5, // 单位精度
      replace: true, // 替换 px 为 rem
      mediaQuery: false, // 不转换媒体查询中的单位
      minPixelValue: 1, // 最小像素值
      exclude: /node_modules/i, // 排除 node_modules,如果是多个 [/node_modules/, /public/], // 排除 node_modules 和 public 目录
    },
  },
};

3.配置 webpack

// vue.config.js
module.exports = {
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          require('autoprefixer'),
          require('postcss-pxtorem')({
            rootValue: 16, // 1rem = 16px
            propList: ['*'], // 转换所有属性
            unitPrecision: 5, // 单位精度
            replace: true, // 替换 px 为 rem
            mediaQuery: false, // 不转换媒体查询中的单位
            minPixelValue: 1, // 最小像素值
            exclude: /node_modules/i, // 排除 node_modules
          }),
        ],
      },
    },
  },
};

4.监测屏幕缩放动态设置根元素

// src/utils/adjustFontSize.js
function adjustFontSize() {
  // 获取屏幕宽度
  const screenWidth = window.innerWidth || document.documentElement.clientWidth;

  // 根据屏幕宽度设置根元素的字体大小
  // 假设我们想要每 100px 屏幕宽度对应 1rem
  const baseFontSize = 16; // 默认的字体大小
  const customFontSize = (screenWidth / 1920) * baseFontSize;

  // 设置 html 的字体大小
  document.documentElement.style.fontSize = `${customFontSize}px`;
}

// 初始化
adjustFontSize();

// 监听窗口大小改变事件
window.addEventListener('resize', adjustFontSize);

5.在 Vue.js 应用中导入和使用 adjustFontSize

//main.js
import './utils/adjustFontSize';

项目中开发时就可以用px开发啦

注意:
在大屏开发中,如果是行内样式的px,不会被进行转换,所以考虑手动转换(echarts中设置grid时就因为没有手动转换rem,导致第一次测试时样式跑偏)

pxToRem.fontSize = function (res){
    const clientWidth= window.innerWidth || window.documentElement.clientWidth || document.body.clientWidth;
    if(clientWidth){
         return
    }
    let fontSize =  clientWidth/1920;
    return res*fontSize
}

使用时:pxToRem.fontSize(80)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值