vue项目使用zoom进行屏幕适配,彻底解决不同屏幕尺寸下的适配痛点

之前写过一篇transform:scale适配的文章,快捷入口:
浏览器适配方案-scale缩放适配【解决留白和全屏模式下的适配问题】

zoom适配相比较scale适配,可以解决scale等比缩放留白的问题,可以解决scale非等比缩放字体变形的问题,但是性能消耗较大,因为重排了,scale只会重绘

封装zoom-box.vue组件

<template>
  <div class="zoom-box-container">
    <div ref="zoom-box" class="zoom-box">
      <!-- 放入的自定义的页面内容 -->
      <slot></slot>
    </div>
  </div>
</template>
<script>
import debounce from "lodash.debounce";
// ui设计稿相关的宽
let WINDTH = 1920;
export default {
  name: "ScaleBox",
  data() {
    return {
      debounceResize: debounce(this.resize, 300),
    };
  },
  mounted() {
    // 初始化执行一次resize方法
    this.resize();
    // 处理浏览器缩放事件
    window.addEventListener("resize", this.debounceResize);
  },
  beforeDestroy() {
    // 移除浏览器缩放事件
    window.removeEventListener("resize", this.debounceResize);
  },
  methods: {
    // 监听浏览器 resize 事件
    resize() {
      this.$nextTick(() => {
        // 判断是否是全屏
        let isFullscreen = window.innerHeight === window.screen.height;
        // 如果是全屏,设计稿高就是1080否则就是914,因为浏览器会有搜索栏和页签
        let HEIGHT = isFullscreen ? 1080 : 914;
        const zoom = this.getZoom();
        const zoomBoxRef = this.$refs["zoom-box"];
        if (zoomBoxRef) {
          zoomBoxRef.style.zoom = zoom;
        }
      });
    },
    // 根据浏览器大小推断缩放比例
    getZoom() {
      // 判断是否是全屏
      let isFullscreen = window.innerHeight === window.screen.height;
      // 如果是全屏蓝湖的高就是1080否则就是914,因为浏览器会有搜索栏和页签
      let HEIGHT = isFullscreen ? 1080 : 914;
      let ww = window.innerWidth / WINDTH;
      let wh = window.innerHeight / HEIGHT;
      return ww < wh ? ww : wh;
    },
  },
};
</script>
<style lang="scss" scoped>
.zoom-box-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  .zoom-box {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
  }
}
</style>
  • 使用
<template>
  <ZoomBox>
    <div class="workbenches"></div>
  </ZoomBox>
</template>
<script>
import ZoomBox from "@/components/zoom-box/index.vue";
export default {
  components: {
    ZoomBox,
  },
};
</script>
<style scoped lang="scss">
.workbenches {
  width: 100%;
  height: 100%;
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值