How to detect page zoom level in all modern browsers?

后端 未结 28 1768
慢半拍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:02

    This is for Chrome, in the wake of user800583 answer ...

    I spent a few hours on this problem and have not found a better approach, but :

    • There are 16 'zoomLevel' and not 10
    • When Chrome is fullscreen/maximized the ratio is window.outerWidth/window.innerWidth, and when it is not, the ratio seems to be (window.outerWidth-16)/window.innerWidth, however the 1st case can be approached by the 2nd one.

    So I came to the following ...

    But this approach has limitations : for example if you play the accordion with the application window (rapidly enlarge and reduce the width of the window) then you will get gaps between zoom levels although the zoom has not changed (may be outerWidth and innerWidth are not exactly updated in the same time).

    var snap = function (r, snaps)
    {
        var i;
        for (i=0; i < 16; i++) { if ( r < snaps[i] ) return i; }
    };
    var w, l, r;
    w = window.outerWidth, l = window.innerWidth;
    return snap((w - 16) / l,
                [ 0.29, 0.42, 0.58, 0.71, 0.83, 0.95, 1.05, 1.18, 1.38, 1.63, 1.88, 2.25, 2.75, 3.5, 4.5, 100 ],
    );
    

    And if you want the factor :

    var snap = function (r, snaps, ratios)
    {
        var i;
        for (i=0; i < 16; i++) { if ( r < snaps[i] ) return eval(ratios[i]); }
    };
    var w, l, r;
    w = window.outerWidth, l = window.innerWidth;
    return snap((w - 16) / l,
                [ 0.29, 0.42, 0.58, 0.71, 0.83, 0.95, 1.05, 1.18, 1.38, 1.63, 1.88, 2.25, 2.75, 3.5, 4.5, 100 ],
                [ 0.25, '1/3', 0.5, '2/3', 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5 ]
    );
    

提交回复
热议问题