大屏自适应,手写PxToRem插件

364 阅读1分钟

最近做到大屏+地图的项目,发现很多自适应的插件都不能同时适配地图跟大屏,手写了一个PxToRem类似的插件 PxToRem.js的代码如下:

image.png

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里面引入:

image.png

image.png

在页面使用自适应样式:

image.png

image.png 传入数字就可以