前端分辨率自适应开发

81 阅读1分钟

tutieshi_640x360_7s.gif

废话不多说,上代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }

  :root {
    --themeColor: #CC1424;
    --themeColor2: #272727;
    --fontNum: 20px;
  }

  html {
    height: 100%;
    user-select: none;
  }

  body {
    font: 1em/1.4 'Microsoft Yahei', 'PingFang SC', 'Avenir', 'Segoe UI', 'Hiragino Sans GB', 'STHeiti', 'Microsoft Sans Serif', 'WenQuanYi Micro Hei', sans-serif;
    font-size: var(--fontNum);
    height: 100%;
    color: black;
    overflow: hidden;

  }


  .routeBox1 {
    width: 100%;
    height: 100%;
    padding: 20px;
    overflow: auto;
  }

  .boxMain {
    background-color: antiquewhite;
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .box {
    /* width: 5.2%;
       height: 0;
       padding-bottom:5.2%; 宽高相同比例 */
    background-color: red;
    color: #fff;
    width: 300px;
    height: 200px;
    font-size: 16px;
  }

  .box2 {
    position: absolute;
    top: 100px;
    left: 100px;
    transition: all .3s;
    width: 400px;
    height: 300px;
    font-size: 18px;
    color: #fff;
    background-color: rgb(25, 0, 255);
  }
</style>

<body>
  <!-- 根元素 -->
  <div id="root">
    <!-- 模拟一个路由页面 -->
    <div class="routeBox1">
      <div class="boxMain">
        <div class="box">我是一段文</div>
        <div class="box2">
          我是一段文字呵呵呵呵
        </div>
      </div>

    </div>
  </div>
</body>

<script>
  // 设计图按照 1920 X 919 来开发
  const planSize = {
    width: 1920,
    height: 919,
  };

  const rootDom = document.querySelector('#root')

  rootDom.style.width = planSize.width + "px";
  rootDom.style.height = planSize.height + "px";

  const pageFullChangeFu = () => {
    const width = window.innerWidth;

    // 屏幕改变的时候改变字体大小
    // // 1920 = 16px
    // const bei = 1920 / 16;
    // let res = Math.round(width / bei);

    // if (res <= 10) res = 10;

    // rootRef.current.style.setProperty("--fontNum", res + "px");

    const height = window.innerHeight;
    const sizeW = width / planSize.width;
    const sizeH = height / planSize.height;

    const moveX = (planSize.width - width) / 2;
    const moveY = (planSize.height - height) / 2;

    rootDom.style.transform = `translate(${-moveX}px,${-moveY}px) scale(${sizeW},${sizeH})`;

  }

  pageFullChangeFu()

  window.addEventListener("resize", pageFullChangeFu, false);
</script>

</html>