vue3+vite+amfe-flexible+postcss-pxtorem 实现全分辨率自适应

打印 上一主题 下一主题

主题 1726|帖子 1726|积分 5178

使用背景

在项目开发过程中,需要自适应多个分辨率,但是我目前按照设计稿开发出1920*1080的界面,为了快速实现自适应多个分辨率的目的,引用本组件
1.使用插件

  1. npm install amfe-flexible --save
  2. npm install postcss-pxtorem autoprefixer --save-dev
复制代码
2.使用

2.1 编写自定义脚本,适配全分辨率

文件名称: flexible.js
文件路径: src/utils/flexible.js
  1. // 增强版适配方案(支持PC+移动)
  2. (function (window, document) {
  3.     const docEl = document.documentElement
  4.     const dpr = window.devicePixelRatio || 1
  5.   
  6.     // 设置body基准字体
  7.     function setBodyFontSize() {
  8.       if (document.body) {
  9.         document.body.style.fontSize = 12 * dpr + 'px'
  10.       }
  11.     }
  12.   
  13.     // 动态计算rem基准值
  14.     function setRemUnit() {
  15.       const clientWidth = docEl.clientWidth
  16.       let baseSize = 16 // 默认基准值
  17.   
  18.       // 多分辨率适配策略
  19.       if (clientWidth < 768) {
  20.         baseSize = (clientWidth / 375) * 16 // 移动端适配
  21.       } else if (clientWidth < 1920) {
  22.         baseSize = (clientWidth / 1920) * 16 // PC端等比缩小
  23.       } else {
  24.         baseSize = (clientWidth / 1920) * 16 // 大屏等比放大
  25.       }
  26.   
  27.       docEl.style.fontSize = baseSize + 'px'
  28.     }
  29.   
  30.     // 初始化设置
  31.     setBodyFontSize()
  32.     setRemUnit()
  33.   
  34.     // 监听事件
  35.     window.addEventListener('resize', setRemUnit)
  36.     window.addEventListener('pageshow', (e) => {
  37.       if (e.persisted) {
  38.         setRemUnit()
  39.       }
  40.     })
  41. })(window, document)
复制代码
2.2 编写设置文件

文件名称:postcss.config.js
文件路径:根目录
  1. // 布局自适应配置
  2. export default {
  3.     plugins: {
  4.       'postcss-pxtorem': {
  5.         rootValue: 16, // 设计稿宽度 1920px 时,1rem = 192px
  6.         propList: ['*'], // 所有属性都转换
  7.         selectorBlackList: ['.ignore-rem'] // 忽略某些选择器
  8.       },
  9.       autoprefixer: {} // 自动添加浏览器前缀
  10.     }
  11. }
复制代码
2.3 main.js 引入 flexible.js文件

必须比其他css样式先引入,要否则不见效
  1. // 引入flexible 自适应
  2. import '@/utils/flexible'
复制代码
2.4 vite.config.js 设置 css剖析

  1. export default defineConfig(({ mode }) => {
  2.   return {
  3.     css: {
  4.       postcss: './postcss.config'// 显式声明配置路
  5.     },
  6.   }
  7. })
复制代码
2.5 index.html引入

  1. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
复制代码
3. 修改文件以及对应目录


4. 实现的结果

实现的话再批评区扣1,SQ

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

飞不高

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表