最近做到大屏+地图的项目,发现很多自适应的插件都不能同时适配地图跟大屏,手写了一个PxToRem类似的插件 PxToRem.js的代码如下:
const fixWidth = 1920;
const fixHeight = 1080;
const fixAspectRatio = fixWidth / fixHeight;
export const getScale = (val = 100) => {
const width = document.documentElement.clientWidth;
const height = document.documentElement.clientHeight;
const scale = width / height < fixAspectRatio ? width / fixWidth : height / fixHeight;
return Math.min(scale, 2) * val;
};
/**
* px转rem 动态设置font-size
*/
export default () => {
const { documentElement } = document;
// console.log('document.documentElement.clientWidth', document.documentElement.clientWidth);
// console.log('document.documentElement.clientHeight', document.documentElement.clientHeight);
// console.log('screen.width', window.screen.width);
// console.log('screen.height', window.screen.height);
documentElement.style.fontSize = `${getScale()}px`;
window.onresize = function () {
documentElement.style.fontSize = `${getScale()}px`;
};
};
在mini.js里面引入:
在页面使用自适应样式:
传入数字就可以