屏幕适配方案

129 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>大屏适配方案</title>
  <style>
    * {
      margin: 0;
      height: 0;
    }
    #app {
      background-color: red;
      /* 这里必须设置好宽高,跟设计稿保持一致 */
      width: 1920px;
      height: 968px;
      /* 通过定位和平移, 让页面内容保持居中 */
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      /* 修改transform的参照点, 默认是中心点,如果不修改的话会相对于设计稿居中
          只有通过这样让其相对于左上角操作再通过上面的方法才能保持在任何屏幕都居中显示
      */
      transform-origin: left top;
    }
  </style>
</head>

<body>
  <div id="app"></div>
  <script>
    // * 设计稿尺寸
    let baseWidth = 1920
    let baseHeight = 968  // 这是减去浏览器顶部导航栏的高度之后的结果
    // let baseHeight = 1080
    let timer = null  // 定时器

    // * 设计稿宽高比 1.77778
    let baseRate = (baseWidth / baseHeight).toFixed(5)

    // * 缩放比例
    let scale = {
      width: '1',
      height: '1'
    }

    const resizeDraw = () => {
      // 获取当前宽高
      let innerWidth = window.innerWidth
      let innerHeight = window.innerHeight
      // 获取当前宽高比
      let innerRate = parseFloat((innerWidth / innerHeight).toFixed(5))
      if (innerRate > baseRate) {
        // 说明屏幕更宽
        let rate = (innerHeight / baseHeight).toFixed(5)
        scale.width = rate
        scale.height = rate
      } else {
        // 说明屏幕更高
        let rate = (innerWidth / baseWidth).toFixed(5)
        scale.width = rate
        scale.height = rate
      }
      document.getElementById("app").style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
    }

    const resize = () => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        resizeDraw()
      }, 200)
    }

    resizeDraw()
    window.addEventListener('resize', resize)
  </script>
</body>

</html>

!!! 尽量不要用vh、vw这种单位,否则 resize 后会有问题