ZengTao
2025-04-16 0c229d95d6442820b4d2d2cd5bcdf3ce1cf069b6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class DevicePixelRatio {
    constructor() {
      this.bodyElement = document.getElementsByTagName('body')[0]; // 缓存 body 元素
    }
  
    // 判断是否为 Windows 系统
    isWindowsSystem() {
      const agent = navigator.userAgent.toLowerCase();
      return agent.indexOf("windows") >= 0;
    }
  
    // 通用事件绑定工具
    addHandler(element, type, handler) {
      if (element.addEventListener) {
        element.addEventListener(type, handler, false);
      } else if (element.attachEvent) {
        element.attachEvent("on" + type, handler);
      } else {
        element["on" + type] = handler;
      }
    }
  
    // 校正浏览器缩放比例
    correctZoom() {
      if (this.bodyElement) {
        // 使用 1 / window.devicePixelRatio 来调整 zoom
        this.bodyElement.style.zoom = 1 / window.devicePixelRatio;
      }
    }
  
    // 监听页面缩放(使用防抖优化)
    watchResize() {
      let timer = null;
      this.addHandler(window, 'resize', () => {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          this.correctZoom();
        }, 200); // 延迟 200ms 执行,避免频繁触发
      });
    }
  
    // 初始化页面比例校正
    init() {
      if (this.isWindowsSystem()) {
        // 初始化校正
        this.correctZoom();
        // 开启监听
        this.watchResize();
      }
    }
  }
  
  export default DevicePixelRatio;