vue适配不同dpi和分辨率

文章介绍了一个JavaScript函数detectZoom,用于检测浏览器的缩放比例。在Vue项目中,这个函数被挂载到Vue.prototype上,以便在App.vue组件中使用。当页面加载或窗口尺寸改变时,会调用getZoomSize方法,根据检测到的缩放比例调整文档的zoom属性,确保显示的清晰度。同时,getZoomSize方法使用防抖(debounce)函数来优化性能,防止频繁触发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

util文件

export const detectZoom = () => {
    let ratio = 0,
      screen = window.screen,
      ua = navigator.userAgent.toLowerCase();
    if (window.devicePixelRatio !== undefined) {
      ratio = window.devicePixelRatio;
    } else if (~ua.indexOf('msie')) {
      if (screen.deviceXDPI && screen.logicalXDPI) {
        ratio = screen.deviceXDPI / screen.logicalXDPI;
      }
    } else if (
      window.outerWidth !== undefined &&
      window.innerWidth !== undefined
    ) {
      ratio = window.outerWidth / window.innerWidth;
    }
    if (ratio) {
      ratio = Math.round(ratio * 100);
    }
    return ratio;
  };

在main.js里面引入挂载

import { detectZoom } from '@/utils/detectZoom.js';
Vue.prototype.detectZoom = detectZoom

在App.vue

	methods() {
		getZoomSize() {
	      let m = this.detectZoom()
	      document.body.style.zoom = 100 / Number(m);
	    },
		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);
	        };
	    },
	}
	mounted() {
	   this.getZoomSize()
	   window.addEventListener("resize", this.debounce(this.getZoomSize));
	},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值