不侵入代码的rem适配,支持桌面缩放,vue2的适配方案,包含echarts适配

此方式不侵入代码,自动把px单位转换成rem单位

首先安装postcss-pxtorem@5.1.1

yarn add postcss-pxtorem@5.1.1
npm install postcss-pxtorem@5.1.1 --save

项目根目录新建 postcss.config.js

module.exports = {
    plugins: {
        'postcss-pxtorem': {
            rootValue: 14,
            propList: ['*'],
        },
    },
};

utils目录下新建rem.js和detectZoom.js并引入main.js中,引入方式

...
import '@/utils/rem'
import { detectZoom } from '@/utils/detectZoom';
const m = detectZoom();
document.body.style.zoom = 100 / Number(m);
...

detectZoom.js

export const detectZoom = () => {
  let ratio = 0,
    screen = window.screen,
    ua = navigator.userAgent.toLowerCase();
  if (window.devicePixelRatio !== undefined) {
    ratio = window.devicePixelRatio;
  } else if (~ua.indexOf('msie')) {
    if (screen.deviceXDPI && screen.logicalXDPI) {
      ratio = screen.deviceXDPI / screen.logicalXDPI;
    }
  } else if (
    window.outerWidth !== undefined &&
    window.innerWidth !== undefined
  ) {
    ratio = window.outerWidth / window.innerWidth;
  }
  if (ratio) {
    ratio = Math.round(ratio * 90);
  }
  return ratio;
};

rem.js

const baseSize = 14; //跟postcss.config.js中rootValue的值是一致的
// 设置 rem 函数
function setRem() {
    // // 当前页面宽度相对于 1920 宽的缩放比例,可根据自己需要修改。
    const scale = document.documentElement.clientWidth / 1920;
    // // 设置页面根节点字体大小 最高为两倍图 即设计稿为750
    document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + "px";
}
// 初始化
setRem();
// 改变窗口大小时重新设置 rem
window.onresize = function () {
    setRem();
};

echarts字体适配方法

/**
 *根据分辨率大小缩放echarts的字体大小
 * @param {*} res
 * @returns
 */
export function fontSize(res) {
  let docEl = document.documentElement,
    clientWidth =
      window.innerWidth ||
      document.documentElement.clientWidth ||
      document.body.clientWidth;
  if (!clientWidth) return;
  let fontSize = 1 * (clientWidth / 1920);
  return res * fontSize;
}

已知问题

  •  detectZoom.js引入后echarts图表会错位不受控,不引入即可。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值