根据屏幕大小的变化自动缩放元素的宽高,达到可以适应任何屏幕大小的效果。
这边通过一个mixins.js文件混入到组件内直接使用就行,只需要改一下ref的名字

示例结构

这里只需要看下我的结构大概示例和引入mixins文件,

<template>
  <div style="width:100%;height:100%;position: relative">
    <div class="box" ref="zoom">
      <p>测试11</p>
      <p>测试22</p>
      <p>测试33</p>
    </div>
  </div>
</template>

<script>
//引入自适应缩放文件
import drawMixin from "@/utils/drawMixin.js";
export default {
  //注册mixin
  mixins: [drawMixin],
};
</script>

<style scoped>
/* 子集盒子的class */
.box {
  /*父级宽100vw,高100vh。子盒子宽高1920*1080可以做大屏显示居中缩放 */
  width: 1500px;
  height: 800px;
  /* 根据父级定位,配合transform用来居中 */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  background-color: red;
  color: #fff;
  /* 更改转换元素的位置 */
  transform-origin: left top;
  /* 超出隐藏 */
  overflow: hidden;
}
</style>

mixin.js文件

这里就直接整个代码原封不动复制过去,找个地方创建一个js文件。名字自己取一下,然后你需要的组件内mixins引入就能用了。

注意点:calcRate 方法内的$refs是绑定你的组件内缩放的元素的,名字注意改一下。

如果你需要缩放的是整个页面,那就把最外层的div取个ref名字写在这里就可以了。

// 屏幕适配 mixin 函数

// * 默认缩放值
const scale = {
  width: '1',
  height: '1',
}

// * 设计稿尺寸(px)
const baseWidth = 1920
const baseHeight = 1080
// * 需保持的比例(默认1.77778)
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))

export default {
  data() {
    return {
      // * 定时函数
      drawTiming: null
    }
  },
  mounted () {
    //加载后先计算一遍缩放比例
    this.calcRate()
    //生成一个监听器:窗口发生变化从新计算计算一遍缩放比例
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    calcRate () {
      //拿到整个页面元素
      const appRef = this.$refs["zoom"]
      //如果没有值就结束
      if (!appRef) return 
      // 当前宽高比
      const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
      //判断:如果有值代表页面变化了
      if (appRef) {
        //判断当前宽高比例是否大于默认比例
        if (currentRate > baseProportion) {
          scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
          scale.height = (window.innerHeight / baseHeight).toFixed(5)
          //整个页面的元素样式,缩放宽高用当前同比例放大的宽高
          appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
        } else {
          scale.height = ((window.innerWidth / baseProportion) / baseHeight).toFixed(5)
          scale.width = (window.innerWidth / baseWidth).toFixed(5)
          appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
        }
      }
    },
    resize () {
      //先清除计时器
      clearTimeout(this.drawTiming)
      //开启计时器
      this.drawTiming = setTimeout(() => {
        this.calcRate()
      }, 200)
    }
  },
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐