1
  • 需求:

    数据大屏页面,适配各种尺寸的PC显示屏幕(不同宽高比),存在全屏时和非全屏时高度变化影响。并且有许多需要absolute定位的元素。

  • 思路:

    absolute的元素用一个div包裹,里面全部用px做单位,用scale放大缩小。

  • 使用过的办法:

    • vw, vh, vmin, vmax: 相当于是百分比,效果不是特别理想,设计稿与各个屏幕的宽高比不同,会存在图片变形或者超出可视范围;
    • rem: 也不理想,不能单纯的靠屏幕宽度,宽度一致时,高度变化,也应该尽可能的铺满;
    • absolute + px + scale: 通过计算视口的宽高按比例缩放。
  • 实现js

     window.onload = function () {
      calScale();
    }
    
    window.addEventListener('resize', function () {
      calScale(); // 建议加个防抖
    })
    
    function calScale() {
      // container 需要的宽高
      const containerHeight = 880, containerWidth = 750;
      // header 导航
      let header = document.querySelectorAll('.header')[0], 
        container = document.querySelectorAll('.container')[0];
    
      let width = document.documentElement.clientWidth,
        height = document.documentElement.clientHeight,
        resetHeight = height - header.offsetHeight;
    
      let zoom;
      if (width > containerWidth) {
        // 宽度足够时, 根据高度缩放
        zoom = (resetHeight / containerHeight).toFixed(2)
      } else if (resetHeight > containerHeight) {
        // 高度足够时,根据宽度缩放
        zoom = (width / containerWidth).toFixed(2)
      }
    
      container.style.transform = 'scale(' + zoom + ')'
    }

myloverhxx
10 声望0 粉丝