js 判断浏览器是否缩放

1,756 阅读1分钟

背景:用 js 判断浏览器是否处于缩放状态

>>> 打印 100 是默认缩放级别,大于 100 是放大,小于 100 是缩小。

代码如下:

function detectZoom (){
  var 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;
};
let result = detectZoom()
console.log(result);

参考链接