此方式不侵入代码,自动把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图表会错位不受控,不引入即可。