大屏rem适配方案

616 阅读1分钟

方案一

第一步

  • 首先安装 @njleonzhang/postcss-px-to-rem 这个包

第二步

  • 配置.postcssrc.js文件
module.exports = {
  plugins: {
    autoprefixer: {},
    "@njleonzhang/postcss-px-to-rem": {
      unitToConvert: 'px', // (String) 要转换的单位,默认是px。
      widthOfDesignLayout: 1920, // (Number) 设计布局的宽度。对于pc仪表盘,一般是1920.
      unitPrecision: 3, // (Number) 允许 REM 单位增长到的十进制数字.
      selectorBlackList: ['.ignore', '.hairlines'], // (Array) 要忽略并保留为 px 的选择器.
      minPixelValue: 1, // (Number) 设置要替换的最小像素值.
      mediaQuery: false // (Boolean) 允许在媒体查询中转换 px.
    }
  }
}
  • 配置完成后,页面内的px就会被转换成rem了

第三步

  • 新建一个rem.js文件,在入口中引入,用于动态计算font-size
(function init(screenRatioByDesign = 16 / 9) {
  let docEle = document.documentElement
  function setHtmlFontSize() {
    var screenRatio = docEle.clientWidth / docEle.clientHeight;
    var fontSize = (
      screenRatio > screenRatioByDesign
        ? (screenRatioByDesign / screenRatio)
        : 1
    ) * docEle.clientWidth / 10;
    docEle.style.fontSize = fontSize.toFixed(3) + "px";
    console.log(docEle.style.fontSize);
  }
  setHtmlFontSize()
  window.addEventListener('resize', setHtmlFontSize)
})()

main.js中引入就可以了

方案二(完美方案)

<template>
  <div id="app">
    <div id="screen"
      :style="{ 'width': `${style.width}px`, 'height': `${style.height}px`, 'transform': `${style.transform}` }">
      <span class="leftTop">左上角</span>
      <span class="rightBottom">右下角</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      style: {
        width: 1920,
        height: 1080,
        transform: "scaleY(1) scaleX(1) translate(-50%, -50%)"
      }
    };
  },
  methods: {
    setScale() {
      const x = window.innerWidth / this.style.width;
      const y = window.innerHeight / this.style.height;
      this.style.transform = `scaleY(${y}) scaleX(${x}) translate(-50%, -50%)`;
    },
  },
  mounted() {
    let that = this;
    that.setScale();
    /*窗口改变事件*/
    window.onresize = () => {
      that.setScale();
    };
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
}

#screen {
  width: 1920px;
  height: 1080px;
  background-color: #bfa;
  position: relative;
  z-index: 100;
  transform-origin: 0 0;
  position: fixed;
  left: 50%;
  top: 50%;
  transition: 0.3s;

}

.leftTop {
  position: absolute;
  left: 0;
  top: 0;
}

.rightBottom {
  position: absolute;
  right: 0;
  bottom: 0;
}
</style>

方案三

display: grid;
grid-template-columns: 300px 1fr 350px;