实现大屏自适应

117 阅读1分钟

``

```<template>
  <div class="scale-wrapper" :style="{ background : wrapperBackground }">
    <div class="scale-box" :style="{ 'background-image' : scaleBackground }" ref="scale-box">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ScaleBox',
  props: {
    width: {
      type: Number,
      default: 1920
    },
    height: {
      type: Number,
      default: 1080
    },
    wrapperBackground: {
      type: String,
      default: '#ffffff'
    },
    scaleBackground: {
      type: String,
      default: '#ffffff'
    }
  },
  data() {
    return {
      scale: null
    }
  },
  mounted() {
    this.setScale()
    window.addEventListener('resize', this.setScale)
  },
  methods: {
    getScale() {
      const { width, height } = this
      const ww = window.innerWidth / width
      const wh = window.innerHeight / height
      return ww < wh ? ww : wh
    },
    setScale() {
      this.scale = this.getScale()
      const ele = this.$refs['scale-box']
      if (ele) {
        ele.style.setProperty('--scale', this.scale)
        ele.style.setProperty('width', `${this.width}px`)
        ele.style.setProperty('height', `${this.height}px`)
      }
    }
  }
}
</script>

<style scoped lang="less">
#scale-box {
  --scale: 1;
}

.scale-wrapper {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.scale-box {
  transform: scale(var(--scale)) translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  transform-origin: 0 0;
  position: absolute;
  left: 50%;
  top: 50%;
  transition: 0.3s;
  z-index: 999;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center;
}
</style>