How to detect page zoom level in all modern browsers?

后端 未结 28 1779
慢半拍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条回答
  •  -上瘾入骨i
    2020-11-21 06:15

    For me, for Chrome/Webkit, document.width / jQuery(document).width() did not work. When I made my window small and zoomed into my site such that horizontal scrollbars appeared, document.width / jQuery(document).width() did not equal 1 at the default zoom. This is because document.width includes part of the document outside the viewport.

    Using window.innerWidth and window.outerWidth worked. For some reason in Chrome, outerWidth is measured in screen pixels and innerWidth is measured in css pixels.

    var screenCssPixelRatio = (window.outerWidth - 8) / window.innerWidth;
    if (screenCssPixelRatio >= .46 && screenCssPixelRatio <= .54) {
      zoomLevel = "-4";
    } else if (screenCssPixelRatio <= .64) {
      zoomLevel = "-3";
    } else if (screenCssPixelRatio <= .76) {
      zoomLevel = "-2";
    } else if (screenCssPixelRatio <= .92) {
      zoomLevel = "-1";
    } else if (screenCssPixelRatio <= 1.10) {
      zoomLevel = "0";
    } else if (screenCssPixelRatio <= 1.32) {
      zoomLevel = "1";
    } else if (screenCssPixelRatio <= 1.58) {
      zoomLevel = "2";
    } else if (screenCssPixelRatio <= 1.90) {
      zoomLevel = "3";
    } else if (screenCssPixelRatio <= 2.28) {
      zoomLevel = "4";
    } else if (screenCssPixelRatio <= 2.70) {
      zoomLevel = "5";
    } else {
      zoomLevel = "unknown";
    }
    

提交回复
热议问题