首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ JavaScript / 文章详情

移动端Rem适配,基于vant

Sonder
2021-01-12
1918字
5分钟
浏览 (3.4k)

vant 项目编写过程中样式直接使用 px作为单位 ,我们可以用工具转化。

1. 引入 flexible 用于设置 rem 基准值

复制代码
// main.js
import './common/flexible'

flexible.js

复制代码
/**
 * 可伸缩布局方案
 * rem计算方式:设计图尺寸px / 100 = 实际rem  例: 100px = 1rem
 */
!(function(window) {
  /* 设计图文档宽度 */
  var docWidth = 750

  var doc = window.document
  var docEl = doc.documentElement
  var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'

  var recalc = (function refreshRem() {
    var clientWidth = docEl.getBoundingClientRect().width

    /* 8.55:小于320px不再缩小,11.2:大于420px不再放大 */
    docEl.style.fontSize = Math.max(Math.min(20 * (clientWidth / docWidth), 11.2), 8.55) * 5 + 'px'

    return refreshRem
  })()

  /* 添加倍屏标识,安卓倍屏为1 */
  docEl.setAttribute('data-dpr', window.navigator.appVersion.match(/iphone/gi) ? window.devicePixelRatio : 1)

  if (/iP(hone|od|ad)/.test(window.navigator.userAgent)) {
    /* 添加IOS标识 */
    doc.documentElement.classList.add('ios')
    /* IOS8以上给html添加hairline样式,以便特殊处理 */
    if (parseInt(window.navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/)[1], 10) >= 8) { doc.documentElement.classList.add('hairline') }
  }

  if (!doc.addEventListener) return
  window.addEventListener(resizeEvt, recalc, false)
  doc.addEventListener('DOMContentLoaded', recalc, false)
}(window))

2. 安装 postcss-pxtorem 用于将单位转化为 rem

$ npm install postcss-pxtorem —save-dev

复制代码
// vue.config.js
const autoprefixer = require('autoprefixer')
const pxtorem = require('postcss-pxtorem')

css: {
 loaderOptions: {
   postcss: {
     plugins: [
       autoprefixer({
         browsers: ['Android >= 4.0', 'iOS >= 7']
       }),
       pxtorem({
         rootValue: 50,
         unitPrecision: 3,
         propList: ['*', '!font*'],
         selectorBlackList: ['.ignore ', '.hairlines', 'van-circle__layer', '.van-hairline'],
         minPixelValue: 2,
       })
     ]
   }
 }
}
下一篇 / PHP图片压缩(比例缩放及尺寸缩放)

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)