常见方案

  • vh、vw方案:将所有的尺寸根据设计图换算成vw和vh
  • scale方案:根据设计图的尺寸和当前屏幕的尺寸计算缩放的比例
  • rem方案:根据设计图和屏幕尺寸计算根元素font-size,其他尺寸通过插件换算成rem

scale兼容的优缺点

优点:1、代码量极少,只需要处理一次container;2、其他各种图表不用单独进行适配
缺点:1、因为是根据ui进行等比例缩放,所以左右和上下可能会出现白边;2、放大倍数过大会导致图片等失真变模糊(可以让ui出8倍的图 然后整体也按照正常分辨率的8倍去编写,这样可以去极大的避免这种情况,缺点就是图片会变得很大,造成图片加载慢);3、缩放之后高德地图,百度地图、echarts等的事件热区会偏移。

代码示例

 1<!DOCTYPE html>
 2<html lang="en">
 3  <head>
 4    <meta charset="UTF-8" />
 5    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 6    <title>Document</title>
 7    <style>
 8      * {
 9        padding: 0;
10        margin: 0;
11      }
12      .demo1 {
13        width: 1920px;
14        height: 1080px;
15        background-color: #f00;
16        transform-origin: top left;
17        margin-left: 50%;
18      }
19    </style>
20  </head>
21  <body style="overflow: hidden; width: 100vw; height: 100vh">
22    <div class="demo1"></div>
23  </body>
24
25  <script>
26    
27     * 计算比例
28     * @param {number} width - 设计图的宽度
29     * @param {number} height - 设计图的高度
30     * @param {HTMLElement} el - 需要应用比例的元素
31     */
32    const calculateRatio = (width, height, el) => {
33      
34      const baseWidth = width;
35      const baseHeight = height;
36      
37      const baseRate = parseFloat(baseWidth / baseHeight).toFixed(5);
38
39      
40      const currentRate = parseFloat(
41        window.innerWidth / window.innerHeight
42      ).toFixed(5);
43
44      
45      const scale = {
46        widthRatio: 1,
47        heightRatio: 1,
48      };
49
50      
51      if (currentRate > baseRate) {
52        
53        scale.widthRatio = parseFloat(
54          ((window.innerHeight * baseRate) / baseWidth).toFixed(5)
55        );
56        scale.heightRatio = parseFloat(
57          (window.innerHeight / baseHeight).toFixed(5)
58        );
59      } else {
60        
61        scale.heightRatio = parseFloat(
62          (window.innerWidth / baseRate / baseHeight).toFixed(5)
63        );
64        scale.widthRatio = parseFloat(
65          (window.innerWidth / baseWidth).toFixed(5)
66        );
67      }
68      
69      el.style.transform = `scale(${scale.widthRatio}, ${scale.heightRatio}) translate(-50%, 0)`;
70    };
71
72    calculateRatio(1920, 1080, document.querySelector(".demo1"));
73
74    window.addEventListener("resize", () => {
75      calculateRatio(1920, 1080, document.querySelector(".demo1"));
76    });
77  </script>
78</html>
79

总结

通过ui图的比例和当前屏幕显示的比例去计算需要缩放的大小倍数,如果当前的屏幕比例大于设计图的比例 那么就是宽度大于高度根据高度去计算缩放 反之则使用宽度去计算

个人笔记记录 2021 ~ 2025