The front end implements large screen scaling and adaptive screen

Front-end implementation of large-screen zoom adaptive screen
idea:

  1. Page initialization gets the original proportion of the screen
  2. Set the adaptive element's scale variable to the current scale
  3. Monitor the browser window size, obtain the new scale value, and reassign the element scale.

vue2—encapsulated code component

<template>
  <div
    class="ScaleBox"
    ref="ScaleBox"
    :style="{
    
    
      width: width + 'px',
      height: height + 'px'
    }"
  >
    <slot></slot>
  </div>
</template>
<script>
export default {
    
    
  props: {
    
    
    // 标准内容宽度
    uiContentWidth: {
    
    
      type: Number,
      default: 1920
    },
    // 标准内容高度
    uiContentHeight: {
    
    
      type: Number,
      default: 0
    },
    // 其他内容的宽度
    otherWidth: {
    
    
      type: Number,
      default: 300 //左侧菜单栏默认宽度,如果没有则忽略
    }
  },
  data () {
    
    
    return {
    
    
      width: 1920, // 初始宽
      height: 1080, // 初始高
      zoom: 1 // 计算要缩放的 宽度比(浏览器可视宽度与设计稿的宽度比)
    }
  },
  mounted () {
    
    
    this.setScale()
    window.addEventListener('resize', this.debounce(this.setScale, 100))
  },
  beforeDestroy () {
    
    
    window.removeEventListener('resize', this.debounce)
  },
  methods: {
    
    
    getScale () {
    
    
      // 当前屏幕下需要适配内容的宽度 = 屏幕的宽度 - 其他不需要适配的内容的宽度
      const innerWidth = window.innerWidth - this.otherWidth
      // 内容元素需要改变的大小比例 = 当前屏幕尺寸需要变化到标准尺寸的比例 / 标准比例
      this.zoom = Number(innerWidth / this.uiContentWidth)
      // 设置缩放后的宽高
      this.width = innerWidth
    },
    setScale () {
    
    
      this.getScale()
      if (this.$refs.ScaleBox) {
    
    
        this.$refs.ScaleBox.style.setProperty('--scaleww', this.zoom)
        this.$refs.ScaleBox.style.setProperty('--scalewh', this.zoom)
      }
    },
    debounce (fn, delay) {
    
    
      const delays = delay || 500
      let timer
      return function () {
    
    
        const th = this
        const args = arguments
        if (timer) {
    
    
          clearTimeout(timer)
        }
        timer = setTimeout(function () {
    
    
          timer = null
          fn.apply(th, args)
        }, delays)
      }
    }
  }
}
</script>

<style lang="scss">
body {
    
    
  &::-webkit-scrollbar {
    
    
    display: none;
  }
}
#ScaleBox {
    
    
  --scaleww: 1;
  --scalewh: 1;
}
.ScaleBox {
    
    
  transform: scale(var(--scaleww), var(--scalewh));
  display: flex;
  flex-direction: column;
  transform-origin: 0 0;
  transition: 0.3s;
  z-index: 3;
}
.no-zoom {
    
    
  transform: scale(var(1 / --scaleww), var(1 / --scalewh));
}
</style>

Guess you like

Origin blog.csdn.net/weixin_45324044/article/details/132813423