大屏兼容之vh、vw

68 阅读2分钟

常见方案

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

vh、vw兼容的优缺点

优点:1、可以动态计算图表的宽高,字体等,灵活性较高;2、当屏幕比例跟ui稿不一致时,不会出现两边留白情况;3、事件的热区,地图点的位置不会飘移
缺点:1、需要设计图尺寸编写Mixin去将px单位换算成vw或vh;2、echarts图标中的距离、文字大小等的单位不支持vw和vh,所以要编写专门的函数将设计图上的尺寸换算成当vw和vh再乘以当前屏幕的宽或高

代码示例

css中的尺寸转换

// 高度适配 1080是设计图的高度
.heightPX(@name,@px) {
    @{name}: @px / (1080 / 100) * 1vh;
}
// 宽度适配 1920是设计图的宽度
.widthPX(@name,@px) {
    @{name}: @px / (1920 / 100) * 1vw;
}


// 在其它地方使用时 需要把上面的代码引入到less文件中 如果每个文件都去引入会很麻烦 所以可以去修改webpack的配置帮我们完成这一步
// webpack里面的lessLoader配置
   lessLoader: {
        javascriptEnabled: true,
        math: 'always',
        modifyVars: {
            // 或者可以通过 less 文件覆盖(文件路径为绝对路径)
            hack: `true; @import "~@/layouts/mixins.less";`
        }
    }
    
    
    
// 在其它样式文件中使用这两个混入时
 .heightPX(height,75);
 .widthPX(width,884);

js代码中尺寸转换

const convertWidthSize = (size: number, defalteWidth = 1920) => {
    const clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    if (!clientWidth) return size;
    const scale = clientWidth / defalteWidth;
    return Number((size * scale).toFixed(3));
};

convertHeightSize = (size: number, defalteWidth = 1080) => {
    const clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    if (!clientHeight) return size;
    const vh = size / (defalteWidth / 100) / 100;
    return Number((vh * clientHeight).toFixed(3));
};


// echarts配置中使用
label: {
         normal: {
            show: true,
            textStyle: {
            color: '#fff',
            fontSize: fitChartSize(14)
                            }
                        }
                    }

总结

大致思路就是将设计图的尺寸换算成vw和vh单位,不能使用vw和vh的放就换算成vw和vh之后再乘以当前屏幕的宽高换算成px

image.png