js 获取屏幕缩放比


    //获取屏幕缩放比例  探针、测距、标签功能都需要
    getRatio() {
      var ratio = 0;
      var screen = window.screen;
      var 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;
    },

 一般是100%,但是笔记本电脑或者别的设备会变化,这样写的代码在笔记本上跑,会出现与本来设定的位置偏移的情况,解决思路就是在写计算方法的时候,计算位置用当前位置除以用户的屏幕缩放比再乘以100

location.style.top = (pos.y / self.getRatio()) * 100 + "px";
location.style.left = (pos.x / self.getRatio()) * 100 + "px";

你可能感兴趣的:(实习笔记,javascript,前端)