解决页面在浏览器缩放样式不同问题,确保在不同缩放级别下页面布局正常

217 阅读1分钟
  1. 现代浏览器:使用 window.devicePixelRatio,它直接返回物理像素与 CSS 像素的比例
  2. IE 浏览器:通过比较设备 DPI 和逻辑 DPI 来计算缩放比例
  3. 备用方法:比较窗口的外部宽度 (outerWidth) 和内部宽度 (innerWidth)

在APP.vue文件中设置

<template>
  <div id="app">
    <router-view :key="key" v-if="isRouterAlive" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      isRouterAlive: true
    };
  },
  computed: {
    key() {
      return this.$route.fullPath
    }
  },
  mounted() {
    this.handleScreen()
  },
  methods: {
    handleScreen() {
      const m = this.detectZoom();
      console.log('屏幕缩放比例', m)
      document.body.style.zoom = 100/Number(m)
    },
    detectZoom () {
      let ratio = 0,
        screen = window.screen,
        ua = navigator.userAgent.toLowerCase();
      
      // 方法1:使用window.devicePixelRatio(现代浏览器支持)
      if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
      } 
      // 方法2:检测IE浏览器(通过screen.deviceXDPI和screen.logicalXDPI)
      else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
          ratio = screen.deviceXDPI / screen.logicalXDPI;
        }
      } 
      // 方法3:比较outerWidth和innerWidth(作为备用方案)
      else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
      }
      
      // 将比例转换为百分比并取整
      if (ratio) {
        ratio = Math.round(ratio * 100);
      }
      
      return ratio;
    }
    
};
</script>

<style type="text/css" media="print">
/* 设置横向打印,支持谷歌,不支持ie */
@page {
  size: landscape;
}
</style>