多分辨率下页面适配(px写死的情况下)

45 阅读1分钟

开发中前端页面使用px写死了布局,但是此时在不同的分辨率下可能出现不同方向的滚动条,且无法根据窗口放大、缩小。

通过监听浏览器窗口size实现不同分辨率下的适配

要求: 1.放大、缩小的时候根据窗口缩放。 2.只允许出现一个方向的滚动条。(纵向)

resize() {
    const designWidth = 1738.18;//正常显示的页面分辨率(宽)
    const designHeight = 1017;//正常显示的页面分辨率(高)
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    
    // 计算宽度的缩放比例
    const widthRatio = windowWidth / designWidth;
    
    // 使用宽度比例进行缩放,确保横向占满
    const multiple = widthRatio;
    
    // 应用缩放
    document.body.style.transform = `scale(${multiple})`;
    document.body.style.transformOrigin = 'top left';
    
    // 调整body的宽度和高度
    document.body.style.width = `${designWidth}px`;
    document.body.style.height = `${designHeight}px`;
    
    // 设置body的margin为0,避免额外的空白
    document.body.style.margin = '0';
    
    // 允许纵向滚动,禁止横向滚动
    document.body.style.overflowX = 'hidden';
    document.body.style.overflowY = 'auto';
    
    // 确保html元素也允许纵向滚动
    document.documentElement.style.overflowY = 'auto';
    
    // 设置图表比例
    window.chartProportion = 1 / multiple;
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.resize);
}

将监听放入mounted方法中

this.resize(); // 使用 this 调用类中的 resize 方法
window.addEventListener("resize", this.resize.bind(this));