当前位置: 首页 > news >正文

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)

相关文章:

  • Modbus-TCP——Libmodbus安装和使用(Ubuntu22.04)
  • 【商城小程序功能概览】
  • 二十二、状态模式
  • 中国社科院-新加坡社科大学商学院联合培养管理学博士
  • 上海晋名气瓶暂存柜助力高校气瓶安全储存
  • 2024UI自动化面试题汇总【建议收藏】
  • 进阶岛 - InternVL 多模态模型部署微调实践
  • 鸿蒙--ArkTS
  • 【开发语言】编译型语言和解释性语言有啥区别?
  • 计算机存储原理——基础
  • Hadoop 中的大数据技术:Zookeeper安装 (2)
  • 国产数据库第一股|万字长文初探达梦 DM8
  • 信号发生器的运行模式有哪些(举例:泰克示波器)
  • Manim动画:相机的移动(MovingCameraScene)
  • 马走日-深度优先搜索
  • Java MessagePack序列化工具(适配Unity)
  • 动态规划(一)
  • 如何优化 Vite 项目中的 Lodash 引入:从 Tree Shaking 到自动化测试
  • Linux权限管理
  • kvm压缩虚拟机磁盘
  • 75岁亚当·费舍尔坐镇,再现80分钟马勒《第九交响曲》
  • 售卖自制外挂交易额超百万元,一男子因提供入侵计算机系统程序被抓
  • 商务部新闻发言人就中美经贸高层会谈答记者问
  • 百亿基金经理调仓路径曝光,张坤、陈皓、胡昕炜又有新动作
  • 江西浮梁县县长张汉坤被查,此前已有4个月无公开活动
  • 中国首位、亚洲首位!赵心童夺得斯诺克世锦赛冠军