当前位置: 首页 > 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 = 16pxpropList: ['*'], // 转换所有属性unitPrecision: 5, // 单位精度replace: true, // 替换 px 为 remmediaQuery: 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 = 16pxpropList: ['*'], // 转换所有属性unitPrecision: 5, // 单位精度replace: true, // 替换 px 为 remmediaQuery: false, // 不转换媒体查询中的单位minPixelValue: 1, // 最小像素值exclude: /node_modules/i, // 排除 node_modules}),],},},},
};

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

// src/utils/adjustFontSize.js
function adjustFontSize() {// 获取屏幕宽度const screenWidth = window.innerWidth || document.documentElement.clientWidth;// 根据屏幕宽度设置根元素的字体大小// 假设我们想要每 100px 屏幕宽度对应 1remconst 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)
http://www.lryc.cn/news/425246.html

相关文章:

  • 如何打造爆款游戏?开发由你操刀,运维交由我托管,合作共赢创造更大成功
  • 颈部按摩仪语音播报芯片方案,高品质语音IC,NV080D
  • Opencv模板匹配
  • JavaScript DOM事件监听器:深入解析与实践应用
  • iOS的App启动详细过程(底层知识)
  • 【轨物推荐】创新者的钥匙:如何破解创新的最大难题
  • SpringCloud的能源管理系统-能源管理平台源码
  • Mybatis获取主键自增的方法
  • strip 、objdump、objcopy 差异与区别
  • 本地phpstudy部署算命系统,用户端是H5页面,支持微信支付宝支付,支持微信支付宝登录
  • APP上架苹果App Store被拒原因及解决方案
  • docker-compose的下载
  • h3c虚拟园区网概述
  • 云原生和安装Ubuntu 22系统
  • HTTP代理IP如何助力旅游大数据领域?怎么建立安全的代理隧道连接?
  • AIGC从入门到实战:基础理论【核心算法与模型】
  • 极狐GitLab 17.2发布了哪些 JH-Only 的功能?
  • css中的高度塌陷
  • 怎样使用sudo的时候不需要输入密码?
  • kettle的Javascript组件获取T-1天和T+1天
  • YoloV8改进策略:Block改进|LeYOLO,一种用于目标检测的新型可扩展且高效的CNN架构|复现LeYolo,轻量级Yolo改进
  • ODX(Open Diagnostic Data Exchange)简介
  • 记一次CSDN认证模块后端未校验漏洞
  • 【图机器学习系列】(一)图机器学习简介
  • 全网最详细,从一堆字符串,精确抓取想要日期时间的实战2.0
  • 24/8/15算法笔记 dp策略迭代 价值迭代
  • 【MMdetection改进】换遍MMDET主干网络之SwinTransformer-Tiny(基于MMdetection)
  • FL Studio21.2.4最新中文版免费下载汉化包破解补丁
  • 私域场景中的数字化营销秘诀
  • 一键换肤(Echarts 自定义主题)