使用背景
在项目开发过程中,需要自适应多个分辨率,但是我目前按照设计稿开发出1920*1080的界面,为了快速实现自适应多个分辨率的目的,引用本组件
1.使用插件
- npm install amfe-flexible --save
- npm install postcss-pxtorem autoprefixer --save-dev
复制代码 2.使用
2.1 编写自定义脚本,适配全分辨率
文件名称: flexible.js
文件路径: src/utils/flexible.js
- // 增强版适配方案(支持PC+移动)
- (function (window, document) {
- const docEl = document.documentElement
- const dpr = window.devicePixelRatio || 1
-
- // 设置body基准字体
- function setBodyFontSize() {
- if (document.body) {
- document.body.style.fontSize = 12 * dpr + 'px'
- }
- }
-
- // 动态计算rem基准值
- function setRemUnit() {
- const clientWidth = docEl.clientWidth
- let baseSize = 16 // 默认基准值
-
- // 多分辨率适配策略
- if (clientWidth < 768) {
- baseSize = (clientWidth / 375) * 16 // 移动端适配
- } else if (clientWidth < 1920) {
- baseSize = (clientWidth / 1920) * 16 // PC端等比缩小
- } else {
- baseSize = (clientWidth / 1920) * 16 // 大屏等比放大
- }
-
- docEl.style.fontSize = baseSize + 'px'
- }
-
- // 初始化设置
- setBodyFontSize()
- setRemUnit()
-
- // 监听事件
- window.addEventListener('resize', setRemUnit)
- window.addEventListener('pageshow', (e) => {
- if (e.persisted) {
- setRemUnit()
- }
- })
- })(window, document)
复制代码 2.2 编写设置文件
文件名称:postcss.config.js
文件路径:根目录
- // 布局自适应配置
- export default {
- plugins: {
- 'postcss-pxtorem': {
- rootValue: 16, // 设计稿宽度 1920px 时,1rem = 192px
- propList: ['*'], // 所有属性都转换
- selectorBlackList: ['.ignore-rem'] // 忽略某些选择器
- },
- autoprefixer: {} // 自动添加浏览器前缀
- }
- }
复制代码 2.3 main.js 引入 flexible.js文件
必须比其他css样式先引入,要否则不见效
- // 引入flexible 自适应
- import '@/utils/flexible'
复制代码 2.4 vite.config.js 设置 css剖析
- export default defineConfig(({ mode }) => {
- return {
- css: {
- postcss: './postcss.config'// 显式声明配置路
- },
- }
- })
复制代码 2.5 index.html引入
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
复制代码 3. 修改文件以及对应目录
4. 实现的结果
实现的话再批评区扣1,SQ
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |