大屏适配

May 01, 2022

适配方案

适用场景

常用数据化大屏的echarts组件和ui组件(不包含高德地图

实现原理

css3的scale可以等比缩放内容并且不会导致元素失帧,所以可以借助动态计算宽高比来确保大屏始终是按照设计稿的宽高比居中显示在显示器内!

使用方法

1. 在需要适配的组件最外侧的容器绑定内联样式

<section class="page-layout">
    <!--  :style="scaleStyle" 则为内联样式  -->
  <section class="page-layout__inner" :class="showBg" :style="scaleStyle">
    <section class="page-layout__inner__header">
      <ScreenTop />
    </section>
    <section class="page-layout__inner__main">
      <ScreenMain />
    </section>
  </section>
  <!-- 高德地图 -->
  <section class="page-layout__map" v-show="showGD" :style="mapBoxStyle">
    <ScreenMap />
  </section>
</section>

2. 定义data数据

data() {
    return {
        scaleStyle: '' // 内联样式
    }
}

3. 在mounted添加load 和resize的事件监听(beforeDestroy记得销毁)

mounted() {
    this.adaptation()
    window.addEventListener('load', this.adaptation)
    window.addEventListener('resize', this.adaptation)
}
beforeDestroy() {
    window.removeEventListener('load', this.adaptation)
    window.removeEventListener('resize', this.adaptation)
},

4. 添加对应的计算适配(缩放比例)的方法

adaptation() {
    this.scaleStyle = this.computedAdaptation() || ''
},
// 计算适配方案
computedAdaptation() {
    const w = document.body.clientWidth
    const h = document.body.clientHeight
    const nw = WINDOW_WIDTH // 1920
    const nh = WINDOW_HEIGHT // 1080
    let scale = 1
    if (w / h > nw / nh) {
        scale = h / nh
    } else {
        scale = w / nw
    }
    const left = (w - WINDOW_WIDTH * scale) / 2
    const top = (h - WINDOW_HEIGHT * scale) / 2
    this.$store.commit('changeScale', scale)
    this.computedMapBoxStyle(scale, top, left)
    return `transform-origin:left top;transform: scale(${scale});width:${WINDOW_WIDTH}px;height:${WINDOW_HEIGHT}px;margin-left:${left}px;margin-top:${top}px`
}
Back