Catch browser's “zoom” event in JavaScript

前端 未结 16 1558
眼角桃花
眼角桃花 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:02

    Lets define px_ratio as below:

    px ratio = ratio of physical pixel to css px.

    if any one zoom The Page, the viewport pxes (px is different from pixel ) reduces and should be fit to The screen so the ratio (physical pixel / CSS_px ) must get bigger.

    but in window Resizing, screen size reduces as well as pxes. so the ratio will maintain.

    zooming: trigger windows.resize event --> and change px_ratio

    but

    resizing: trigger windows.resize event --> doesn’t change px_ratio

    //for zoom detection
    px_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;
    
    $(window).resize(function(){isZooming();});
    
    function isZooming(){
        var newPx_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;
        if(newPx_ratio != px_ratio){
            px_ratio = newPx_ratio;
            console.log("zooming");
            return true;
        }else{
            console.log("just resizing");
            return false;
        }
    }
    

    The key point is difference between CSS PX and Physical Pixel.

    https://gist.github.com/abilogos/66aba96bb0fb27ab3ed4a13245817d1e

提交回复
热议问题