evicePixelRatio.js 1.67 KB
Newer Older
朱国瑞's avatar
朱国瑞 committed
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
/**
 * @description 校正windows页面在系统进行缩放后导致页面被放大的问题,通常放大比例是125%、150%
 * **/

class DevicePixelRatio {
  constructor() {}
  //获取系统类型
  _getSystem() {
    let flag = false;
    var agent = navigator.userAgent.toLowerCase();
    if (agent.indexOf("windows") >= 0) {
      return true;
    }
  }
  //获取页面缩放比例
  _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;
    }
  }
  //校正浏览器缩放比例
  _correct() {
    let t = this;
    //页面devicePixelRatio(设备像素比例)变化后,计算页面body标签zoom修改其大小,来抵消devicePixelRatio带来的变化。
    document.getElementById('main').style.zoom = 1 / window.devicePixelRatio;
30 31 32
    t._bodyScale()
  }
  _bodyScale() {
33
    var scale = window.screen.width / 1920 * 1.25; // 分母——设计稿的尺寸
34
    document.getElementById('main').style.zoom = scale; //放大缩小相应倍数
朱国瑞's avatar
朱国瑞 committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
  }
  //监听页面缩放
  _watch() {
    let t = this;
    t._addHandler(window, 'resize', function () { //注意这个方法是解决全局有两个window.resize
      //重新校正
      t._correct()
    })
  }
  //初始化页面比例
  init() {
    let t = this;
    if (t._getSystem()) { //判断设备,目前只在windows系统下校正浏览器缩放比例
      //初始化页面校正浏览器缩放比例
      t._correct();
      //开启监听页面缩放
      t._watch();
    }
  }
}
export default DevicePixelRatio;