大屏适配方案--scale

发布于:2024-04-25 ⋅ 阅读:(17) ⋅ 点赞:(0)

CSS3的scale等比例缩放

宽度比率 = 当前网页宽度 / 设计稿宽度

高度比率 = 当前网页高度 / 设计稿高度

设计稿: 1920 * 1080

适配屏幕:1920 * 1080 3840 * 2160(2 * 2) 7680 * 2160(4 * 2)

方案一:根据宽度比率进行缩放(超宽屏比如9/16的屏幕会出现滚动条)

方案二:动态计算网页的宽高比,决定根据宽度比率还是高度比率进行缩放

首先基于1920 * 1080进行基础的布局,下面针对两种方案进行实现

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body,
      ul {
        margin: 0;
        padding: 0;
      }
      body {
        width: 1920px;
        height: 1080px;
        box-sizing: border-box;
        
        /* 在js中添加translate居中 */
        position: relative;
        left: 50%;

        /* 指定缩放的原点在左上角 */
        transform-origin: left top;
      }

      ul {
        width: 100%;
        height: 100%;
        list-style: none;

        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
      }

      li {
        width: 33.333%;
        height: 50%;
        box-sizing: border-box;
        border: 2px solid rgb(198, 9, 135);
        font-size: 30px;
      }
    </style>
  </head>
  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
      <li>6</li>
    </ul>

    <script>
      // ...实现适配方案
    </script>
  </body>
</html>

方案一:根据宽度比率进行缩放

// 设计稿尺寸以及宽高比
let targetWidth = 1920;

// html的宽 || body的宽
let currentWidth =
  document.documentElement.clientWidth || document.body.clientWidth;

console.log(currentWidth);
// 按宽度计算缩放比率
let scaleRatio = currentWidth / targetWidth;

// 进行缩放
document.body.style = `transform: scale(${scaleRatio})`;

实现效果如下:

b.gif 这时我们发现在7680 * 2160尺寸下,屏幕根据宽度缩放会出现滚动条,为了解决这个问题,我们就要动态的选择根据宽度缩放还是根据高度缩放。

方案二:动态计算网页的宽高比,决定根据宽度比率还是高度比率进行缩放

// 设计稿尺寸以及宽高比
let targetWidth = 1920;
let targetHeight = 1080;
let targetRatio = 16 / 9; // targetWidth /targetHeight

// 当前屏幕html的宽 || body的宽
let currentWidth =
  document.documentElement.clientWidth || document.body.clientWidth;
// 当前屏幕html的高 || body的高
let currentHeight =
  document.documentElement.clientHeight || document.body.clientHeight;

// 当前屏幕宽高比
let currentRatio = currentWidth / currentHeight;

// 默认 按宽度计算缩放比率
let scaleRatio = currentWidth / targetWidth;
if (currentRatio > targetRatio) {
  scaleRatio = currentHeight / targetHeight;
}

// 进行缩放
document.body.style = `transform: scale(${scaleRatio}) translateX(-50%);`;

效果如下:

b.gif 这样就可以解决在超宽屏幕下出现滚动条的问题,另外我们做了居中的样式处理,这样在超宽屏幕时,两边留白,内容居中展示显得更加合理些。


网站公告

今日签到

点亮在社区的每一天
去签到