How to detect page zoom level in all modern browsers?

后端 未结 28 2396
慢半拍i
慢半拍i 2020-11-21 05:27
  1. How can I detect the page zoom level in all modern browsers? While this thread tells how to do it in IE7 and IE8, I can\'t find a good cross-browser solution.

28条回答
  •  佛祖请我去吃肉
    2020-11-21 06:16

    Have it currently working however still need to separate by browser. Tested successfully on Chrome(75) and Safari(11.1) (haven't found way for FF as of yet). It also gets the zoom value correct on retina display and calculations are triggered on resize event.

        private pixelRatio() {
          const styleString = "(min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 1.5),(-moz-min-device-pixel-ratio: 1.5),(min-device-pixel-ratio: 1.5)";
          const chromeRatio = (Math.round((this.window.outerWidth / this.window.innerWidth)*100) / 100);
          const otherRatio = (Math.round(window.devicePixelRatio * 100) / 100);
          const resizeValue = (this.isChrome()) ? chromeRatio : otherRatio;
    
          return resizeValue || (this.window.matchMedia && this.window.matchMedia(styleString).matches ? 2 : 1) || 1;
        }
    
    
      private isChrome():boolean {
        return (!!this.window.chrome && !(!!this.window.opera || this.window.navigator.userAgent.indexOf(' Opera') >= 0))
      }
    
      private chrome() {
        const zoomChrome = Math.round(((this.window.outerWidth) / this.window.innerWidth)*100) / 100;
        return {
          zoom: zoomChrome,
          devicePxPerCssPx: zoomChrome1 * this.pixelRatio()
        };
      }
    

提交回复
热议问题