Catch browser's “zoom” event in JavaScript

前端 未结 16 1833
眼角桃花
眼角桃花 2020-11-22 05:45

Is it possible to detect, using JavaScript, when the user changes the zoom in a page? I simply want to catch a \"zoom\" event and respond to it (similar to window.onresize e

16条回答
  •  眼角桃花
    2020-11-22 06:12

    Here is a clean solution:

    // polyfill window.devicePixelRatio for IE
    if(!window.devicePixelRatio){
      Object.defineProperty(window,'devicePixelRatio',{
        enumerable: true,
        configurable: true,
        get:function(){
          return screen.deviceXDPI/screen.logicalXDPI;
        }
      });
    }
    var oldValue=window.devicePixelRatio;
    window.addEventListener('resize',function(e){
      var newValue=window.devicePixelRatio;
      if(newValue!==oldValue){
        // TODO polyfill CustomEvent for IE
        var event=new CustomEvent('devicepixelratiochange');
        event.oldValue=oldValue;
        event.newValue=newValue;
        oldValue=newValue;
        window.dispatchEvent(event);
      }
    });
    
    window.addEventListener('devicepixelratiochange',function(e){
      console.log('devicePixelRatio changed from '+e.oldValue+' to '+e.newValue);
    });

提交回复
热议问题