Javascript detects the browser's zoom state implementation code

  • 2020-03-30 04:00:53
  • OfStack

The value returned by the detectZoom function is the default zoom level if it is 100, larger than 100 is zoomed in, and smaller than 100 is zoomed out.


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;
};

Original article, reprint please indicate: Reprinted from (link: http://www.javascript100.com/)


Related articles: