如何在所有现代浏览器中检测页面缩放级别?虽然这篇文章讲述了如何在IE7和IE8中做到这一点,但我找不到一个好的跨浏览器解决方案。 Firefox存储页面缩放级别以供将来访问。在第一页加载,我能得到缩放级别吗?在某个地方,我读到当页面加载后发生缩放变化时,它是有效的。 有办法捕捉'缩放'事件吗?

我需要这个,因为我的一些计算是基于像素的,他们可能会在放大时波动。


@tfl给出的修改样本

放大时,此页面会提示不同的高度值。(jsFiddle)

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"/></script>
    </head>
    <body>
        <div id="xy" style="border:1px solid #f00; width:100px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sollicitudin tortor in lacus tincidunt volutpat. Integer dignissim imperdiet mollis. Suspendisse quis tortor velit, placerat tempor neque. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Praesent bibendum auctor lorem vitae tempor. Nullam condimentum aliquam elementum. Nullam egestas gravida elementum. Maecenas mattis molestie nisl sit amet vehicula. Donec semper tristique blandit. Vestibulum adipiscing placerat mollis.</div>
        <button onclick="alert($('#xy').height());">Show</button>
    </body>
</html>

这里没有变化!:

<html>
 <head>
  <title></title>
 </head>
<body>
 <div id="xy" style="width:400px;">
  foobar
 </div>
 <div>
  <button onclick="alert(document.getElementById('xy').style.width);">Show</button>
 </div>
</body>
</html>

创建一个简单的HTML文件,点击按钮。不管什么缩放级别:它会显示400px的宽度(至少在firefox和ie8上)

您的计算仍然是基于一些CSS像素。现在它们在屏幕上的大小不同了。这就是整页缩放的意义所在。

您希望在192dpi设备上的浏览器上发生什么,因此通常在图像中的每个像素中显示四个设备像素?在50%缩放时,这个设备现在在一个设备像素中显示一个图像像素。

没有在IE中测试这个,但是如果你创建一个元素elem with

min-width: 100%

然后

window.document.width / elem.clientWidth

将为您提供浏览器缩放级别(包括document.body.style.zoom因子)。

在Internet Explorer 7、8和9中,这是有效的:

function getZoom() {
    var screen;

    screen = document.frames.screen;
    return ((screen.deviceXDPI / screen.systemXDPI) * 100 + 0.9).toFixed();
}

添加“+0.9”是为了防止舍入错误(否则,当浏览器缩放分别设置为105%和110%时,您将得到104%和109%)。

在IE6中不存在缩放,所以没有必要检查缩放。

现在的情况比刚提出这个问题时还要糟糕。通过阅读我所能找到的所有回复和博客文章,这里有一个总结。我还设置了这个页面来测试所有这些测量缩放级别的方法。[↑断裂链接。存档副本→此处]。

编辑(2011-12-12):我添加了一个可以克隆的项目:https://github.com/tombigel/detect-zoom

IE8: screen.deviceXDPI / screen.logicalXDPI (or, for the zoom level relative to default zoom, screen.systemXDPI / screen.logicalXDPI) IE7: var body = document.body,r = body.getBoundingClientRect(); return (r.left-r.right)/body.offsetWidth; (thanks to this example or this answer) FF3.5 ONLY: screen.width / media query screen width (see below) (takes advantage of the fact that screen.width uses device pixels but MQ width uses CSS pixels--thanks to Quirksmode widths) FF3.6: no known method FF4+: media queries binary search (see below) WebKit: https://www.chromestatus.com/feature/5737866978131968 (thanks to Teo in the comments) WebKit: measure the preferred size of a div with -webkit-text-size-adjust:none. WebKit: (broken since r72591) document.width / jQuery(document).width() (thanks to Dirk van Oosterbosch above). To get ratio in terms of device pixels (instead of relative to default zoom), multiply by window.devicePixelRatio. Old WebKit? (unverified): parseInt(getComputedStyle(document.documentElement,null).width) / document.documentElement.clientWidth (from this answer) Opera: document.documentElement.offsetWidth / width of a position:fixed; width:100% div. from here (Quirksmode's widths table says it's a bug; innerWidth should be CSS px). We use the position:fixed element to get the width of the viewport including the space where the scrollbars are; document.documentElement.clientWidth excludes this width. This is broken since sometime in 2011; I know no way to get the zoom level in Opera anymore. Other: Flash solution from Sebastian Unreliable: listen to mouse events and measure change in screenX / change in clientX

这里是Firefox 4的二进制搜索,因为我不知道它暴露在哪里:

<style id=binarysearch></style>
<div id=dummyElement>Dummy element to test media queries.</div>
<script>
var mediaQueryMatches = function(property, r) {
  var style = document.getElementById('binarysearch');
  var dummyElement = document.getElementById('dummyElement');
  style.sheet.insertRule('@media (' + property + ':' + r +
                         ') {#dummyElement ' +
                         '{text-decoration: underline} }', 0);
  var matched = getComputedStyle(dummyElement, null).textDecoration
      == 'underline';
  style.sheet.deleteRule(0);
  return matched;
};
var mediaQueryBinarySearch = function(
    property, unit, a, b, maxIter, epsilon) {
  var mid = (a + b)/2;
  if (maxIter == 0 || b - a < epsilon) return mid;
  if (mediaQueryMatches(property, mid + unit)) {
    return mediaQueryBinarySearch(
        property, unit, mid, b, maxIter-1, epsilon);
  } else {
    return mediaQueryBinarySearch(
        property, unit, a, mid, maxIter-1, epsilon);
  }
};
var mozDevicePixelRatio = mediaQueryBinarySearch(
    'min--moz-device-pixel-ratio', '', a, b, maxIter, epsilon);
var ff35DevicePixelRatio = screen.width / mediaQueryBinarySearch(
    'min-device-width', 'px', 0, 6000, 25, .0001);
</script>

对我来说,Chrome/Webkit,文档。width / jQuery(document).width()不能正常工作。当我把我的窗口变小,并放大到我的网站,这样水平滚动条出现,文档。width / jQuery(document).width()在默认缩放时不等于1。这是因为文档。宽度包括视口之外的部分文档。

使用窗口。innerWidth和window。outerWidth工作。在Chrome中,由于某种原因,outerWidth是以屏幕像素为单位,而innerWidth是以css像素为单位。

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";
}

I found this article enormously helpful. Huge thanks to yonran. I wanted to pass on some additional learning I found while implementing some of the techniques he provided. In FF6 and Chrome 9, support for media queries from JS was added, which can greatly simplify the media query approach necessary for determining zoom in FF. See the docs at MDN here. For my purposes, I only needed to detect whether the browser was zoomed in or out, I had no need for the actual zoom factor. I was able to get my answer with one line of JavaScript:

var isZoomed = window.matchMedia('(max--moz-device-pixel-ratio:0.99), (min--moz-device-pixel-ratio:1.01)').matches;

结合IE8+和Webkit解决方案(它们也是单行的),我能够在只有几行代码的情况下检测到绝大多数浏览器的缩放效果。

这可能会或可能不会帮助任何人,但我有一个页面,我不能得到正确的中心,无论什么Css技巧我尝试了,所以我写了一个JQuery文件呼叫中心页面:

问题发生在浏览器的缩放级别,页面会根据您的100%,125%,150%等进行移动。

下面的代码位于一个名为centerpage.js的JQuery文件中。

从我的页面,我必须链接到JQuery和这个文件才能让它工作,即使我的主页已经有一个链接到JQuery。

<title>Home Page.</title>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/centerpage.js"></script>

centerpage.js:

// centering page element
function centerPage() {
    // get body element
    var body = document.body;

    // if the body element exists
    if (body != null) {
        // get the clientWidth
        var clientWidth = body.clientWidth;

        // request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var left = (windowWidth - bodyWidth) / 2;

        // this is a hack, but it works for me a better method is to determine the 
        // scale but for now it works for my needs
        if (left > 84) {
            // the zoom level is most likely around 150 or higher
            $('#MainBody').removeClass('body').addClass('body150');
        } else if (left < 100) {
            // the zoom level is most likely around 110 - 140
            $('#MainBody').removeClass('body').addClass('body125');
        }
    }
}


// CONTROLLING EVENTS IN jQuery
$(document).ready(function() {
    // center the page
    centerPage();
});

如果你想让一个面板居中:

// centering panel
function centerPanel($panelControl) {
    // if the panel control exists
    if ($panelControl && $panelControl.length) {
        // request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;
        var panelHeight = $panelControl.height();
        var panelWidth = $panelControl.width();

        // centering
        $panelControl.css({
            'position': 'absolute',
            'top': (windowHeight - panelHeight) / 2,
            'left': (windowWidth - panelWidth) / 2
        });

        // only need force for IE6
        $('#backgroundPanel').css('height', windowHeight);
    }
}

这是一个很久以前发布的问题,但今天当我在寻找相同的答案“如何检测放大和缩小事件”时,我找不到一个适合所有浏览器的答案。

就像现在一样:对于Firefox/Chrome/IE8和IE9,放大和缩小会触发一个窗口。调整大小事件。 可以使用以下方法捕获:

$(window).resize(function() {
//YOUR CODE.
});

这对我来说在基于webkit的浏览器(Chrome, Safari)中非常有效:

function isZoomed() {
    var width, mediaQuery;

    width = document.body.clientWidth;
    mediaQuery = '(max-width: ' + width + 'px) and (min-width: ' + width + 'px)';

    return !window.matchMedia(mediaQuery).matches;
}

但在Firefox中似乎不能正常工作。

这也适用于WebKit:

var zoomLevel = document.width / document.body.clientWidth;

我的同事和我使用了来自https://github.com/tombigel/detect-zoom的脚本。此外,我们还动态地创建了一个svg元素并检查其currentScale属性。它在Chrome和大多数浏览器上都很好用。在FF上,“仅缩放文本”功能必须关闭。大多数浏览器都支持SVG。在撰写本文时,已在IE10、FF19和Chrome28上进行了测试。

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
svg.setAttribute('version', '1.1');
document.body.appendChild(svg);
var z = svg.currentScale;
... more code ...
document.body.removeChild(svg);

这是针对Chrome的,在user800583回答之后…

我花了几个小时研究这个问题,并没有找到更好的方法,但是:

有16个“zoomLevel”而不是10个 当Chrome是全屏/最大化的比率是window. outerwidth /window。innerWidth,如果不是,比率似乎是(window. outerwidth -16)/window。innerWidth,但是第一种情况可以被第二种情况接近。

所以我想到了下面这些……

但是这种方法有局限性:例如,如果您在应用程序窗口中使用手风琴(快速放大和减小窗口的宽度),那么尽管缩放没有改变(可能outerWidth和innerWidth没有同时更新),但您将在缩放级别之间获得间隙。

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 ],
);

如果你想要因子:

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 ]
);

我想到的是:

1)制作一个位置:固定<div>宽度:100% (id=zoomdiv)

2)页面加载时:

zoomlevel=$("#zoomdiv").width()*1.0 / screen.availWidth

它适用于我的ctrl+和ctrl-缩放。

或者我可以添加一行到$(window).onresize()事件,以获得活动缩放级别


代码:

<script>
    var zoom=$("#zoomdiv").width()*1.0 / screen.availWidth;

    $(window).resize(function(){
        zoom=$("#zoomdiv").width()*1.0 / screen.availWidth;
        alert(zoom);    
    });
</script>
<body>
    <div id=zoomdiv style="width:100%;position:fixed;"></div>
</body>

附注:这是我的第一个帖子,请原谅任何错误

一个变通的FireFox 16+找到DPPX(缩放级别)纯粹与JavaScript:

var dppx = (function (precision) {
  var searchDPPX = function(level, min, divisor) {
    var wmq = window.matchMedia;
    while (level >= min && !wmq("(min-resolution: " + (level/divisor) + "dppx)").matches) {
      level--;
    }
    return level;
  };

  var maxDPPX = 5.0; // Firefox 22 has 3.0 as maximum, but testing a bit greater values does not cost much
  var minDPPX = 0.1; // Firefox 22 has 0.3 as minimum, but testing a bit smaller values does not cost anything
  var divisor = 1;
  var result;
  for (var i = 0; i < precision; i++) {
    result = 10 * searchDPPX (maxDPPX, minDPPX, divisor);
    maxDPPX = result + 9;
    minDPPX = result;
    divisor *= 10;
  }

  return result / divisor;
}) (5);

我有这个解决方案只适用于手机(在Android上测试):

jQuery(function($){

zoom_level = function(){

    $("body").prepend('<div class="overlay" ' +
                'style="position:fixed; top:0%; left:0%; ' +
                'width:100%; height:100%; z-index:1;"></div>');

    var ratio = $("body .overlay:eq(0)").outerWidth() / $(window).width();
    $("body .overlay:eq(0)").remove();

    return ratio;
}

alert(zoom_level());

});

如果你想要缩放级别在缩放移动之后,你可能不得不设置一个小的超时,因为呈现延迟(但我不确定,因为我没有测试它)。

function supportFullCss3()
{
    var div = document.createElement("div");
    div.style.display = 'flex';
    var s1 = div.style.display == 'flex';
    var s2 = 'perspective' in div.style;

    return (s1 && s2);
};

function getZoomLevel()
{
    var screenPixelRatio = 0, zoomLevel = 0;

    if(window.devicePixelRatio && supportFullCss3())
        screenPixelRatio = window.devicePixelRatio;
    else if(window.screenX == '0')
        screenPixelRatio = (window.outerWidth - 8) / window.innerWidth;
    else
    {
        var scr = window.frames.screen;
        screenPixelRatio = scr.deviceXDPI / scr.systemXDPI;
    }

    //---------------------------------------
    if (screenPixelRatio <= .11){ //screenPixelRatio >= .01 &&
      zoomLevel = "-7";
    } else if (screenPixelRatio <= .25) {
      zoomLevel = "-6";
    }else if (screenPixelRatio <= .33) {
      zoomLevel = "-5.5";
    } else if (screenPixelRatio <= .40) {
      zoomLevel = "-5";
    } else if (screenPixelRatio <= .50) {
      zoomLevel = "-4";
    } else if (screenPixelRatio <= .67) {
      zoomLevel = "-3";
    } else if (screenPixelRatio <= .75) {
      zoomLevel = "-2";
    } else if (screenPixelRatio <= .85) {
      zoomLevel = "-1.5";
    } else if (screenPixelRatio <= .98) {
      zoomLevel = "-1";
    } else if (screenPixelRatio <= 1.03) {
      zoomLevel = "0";
    } else if (screenPixelRatio <= 1.12) {
      zoomLevel = "1";
    } else if (screenPixelRatio <= 1.2) {
      zoomLevel = "1.5";
    } else if (screenPixelRatio <= 1.3) {
      zoomLevel = "2";
    } else if (screenPixelRatio <= 1.4) {
      zoomLevel = "2.5";
    } else if (screenPixelRatio <= 1.5) {
      zoomLevel = "3";
    } else if (screenPixelRatio <= 1.6) {
      zoomLevel = "3.3";
    } else if (screenPixelRatio <= 1.7) {
      zoomLevel = "3.7";
    } else if (screenPixelRatio <= 1.8) {
      zoomLevel = "4";
    } else if (screenPixelRatio <= 1.9) {
      zoomLevel = "4.5";
    } else if (screenPixelRatio <= 2) {
      zoomLevel = "5";
    } else if (screenPixelRatio <= 2.1) {
      zoomLevel = "5.2";
    } else if (screenPixelRatio <= 2.2) {
      zoomLevel = "5.4";
    } else if (screenPixelRatio <= 2.3) {
      zoomLevel = "5.6";
    } else if (screenPixelRatio <= 2.4) {
      zoomLevel = "5.8";
    } else if (screenPixelRatio <= 2.5) {
      zoomLevel = "6";
    } else if (screenPixelRatio <= 2.6) {
      zoomLevel = "6.2";
    } else if (screenPixelRatio <= 2.7) {
      zoomLevel = "6.4";
    } else if (screenPixelRatio <= 2.8) {
      zoomLevel = "6.6";
    } else if (screenPixelRatio <= 2.9) {
      zoomLevel = "6.8";
    } else if (screenPixelRatio <= 3) {
      zoomLevel = "7";
    } else if (screenPixelRatio <= 3.1) {
      zoomLevel = "7.1";
    } else if (screenPixelRatio <= 3.2) {
      zoomLevel = "7.2";
    } else if (screenPixelRatio <= 3.3) {
      zoomLevel = "7.3";
    } else if (screenPixelRatio <= 3.4) {
      zoomLevel = "7.4";
    } else if (screenPixelRatio <= 3.5) {
      zoomLevel = "7.5";
    } else if (screenPixelRatio <= 3.6) {
      zoomLevel = "7.6";
    } else if (screenPixelRatio <= 3.7) {
      zoomLevel = "7.7";
    } else if (screenPixelRatio <= 3.8) {
      zoomLevel = "7.8";
    } else if (screenPixelRatio <= 3.9) {
      zoomLevel = "7.9";
    } else if (screenPixelRatio <= 4) {
      zoomLevel = "8";
    } else if (screenPixelRatio <= 4.1) {
      zoomLevel = "8.1";
    } else if (screenPixelRatio <= 4.2) {
      zoomLevel = "8.2";
    } else if (screenPixelRatio <= 4.3) {
      zoomLevel = "8.3";
    } else if (screenPixelRatio <= 4.4) {
      zoomLevel = "8.4";
    } else if (screenPixelRatio <= 4.5) {
      zoomLevel = "8.5";
    } else if (screenPixelRatio <= 4.6) {
      zoomLevel = "8.6";
    } else if (screenPixelRatio <= 4.7) {
      zoomLevel = "8.7";
    } else if (screenPixelRatio <= 4.8) {
      zoomLevel = "8.8";
    } else if (screenPixelRatio <= 4.9) {
      zoomLevel = "8.9";
    } else if (screenPixelRatio <= 5) {
      zoomLevel = "9";
    }else {
      zoomLevel = "unknown";
    }

    return zoomLevel;
};
zoom = ( window.outerWidth - 10 ) / window.innerWidth

这就是你所需要的。

你可以试试

var browserZoomLevel = Math.round(window.devicePixelRatio * 100);

这将给你的浏览器缩放百分比水平在非视网膜显示。对于高DPI/视网膜显示器,它将产生不同的值(例如,Chrome和Safari为200,Firefox为140)。

捕获缩放事件,您可以使用

$(window).resize(function() { 
// your code 
});

截至2016年1月,我有一个解决方案。在Chrome, Firefox和MS Edge浏览器中测试工作。

The principle is as follows. Collect 2 MouseEvent points that are far apart. Each mouse event comes with screen and document coordinates. Measure the distance between the 2 points in both coordinate systems. Although there are variable fixed offsets between the coordinate systems due to the browser furniture, the distance between the points should be identical if the page is not zoomed. The reason for specifying "far apart" (I put this as 12 pixels) is so that small zoom changes (e.g. 90% or 110%) are detectable.

参考: https://developer.mozilla.org/en/docs/Web/Events/mousemove

步骤:

添加一个鼠标移动监听器 窗口。addEventListener("鼠标移动",函数(事件){ //处理事件 }); 从鼠标事件中捕获4个测量值: 事件。clientX、事件。clientY、事件。screenX, event.screenY 测量客户端系统中两点之间的距离d_c 测量屏幕系统中两点之间的距离d_s 如果d_c != d_s,则应用缩放。两者之间的差别告诉你缩放的大小。

注意:很少做距离计算,例如,当你可以采样一个新的鼠标事件,它离前一个事件很远的时候。

限制:假设用户将移动鼠标至少一点,缩放是不可知的,直到这个时候。

基本上,我们有:

devicepixelratio,它同时考虑了浏览器级别的缩放*以及系统缩放/像素密度。 *在Mac/Safari上不考虑缩放级别 媒体查询 vw/vh CSS单位 缩放级别更改时触发的Resize事件,会导致窗口的有效大小更改

这对于正常的用户体验来说应该足够了。如果你需要检测缩放级别,这可能是糟糕UI设计的标志。

音高变焦更难跟踪,目前还没有考虑。

这个答案是基于user1080381的答案上devicePixelRatio返回错误的注释。

我发现在使用台式机、Surface Pro 3和Surface Pro 4时,这个命令在某些情况下也会错误地返回。

我发现它在我的桌面上是有效的,但是SP3和SP4给出的数字是不同的。

不过我注意到,SP3的缩放级别是我预期的1.5倍。当我查看显示设置时,SP3实际上被设置为150%,而不是我桌面上的100%。

因此,注释的解决方案应该是将返回的缩放级别除以当前所在机器的缩放比例。

我可以通过以下方法在Windows设置中获得比例:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");
double deviceScale = Convert.ToDouble(searcher.Get().OfType<ManagementObject>().FirstOrDefault()["PixelsPerXLogicalInch"]);
int standardPixelPerInch = 96;
return deviceScale / standardPixelPerInch;

所以在我的SP3的情况下,这是这段代码在100%缩放时的样子:

devicePixelRatio = 1.5
deviceScale = 144
deviceScale / standardPixelPerInch = 1.5
devicePixelRatio / (deviceScale / standardPixelPerInch) = 1

乘以user1080381的原始答案中的100,然后将得到100(%)的缩放。

问题在于使用的显示器类型,4k显示器和标准显示器。Chrome是迄今为止最聪明的,能够告诉我们缩放级别是什么,只是使用window.devicePixelRatio,显然它可以告诉什么像素密度是什么,并报告相同的数字。

其他浏览器就没有这么多了。IE和Edge可能是最差的,因为它们处理缩放级别的方式大不相同。要在4k显示器上获得相同大小的文本,您必须选择200%,而不是标准显示器上的100%。

截至2018年5月,以下是我检测到的一些最流行的浏览器(Chrome、Firefox和IE11)的缩放级别。我让它告诉我缩放百分比是多少。对于IE,即使4k显示器实际为200%,它也报告为100%,但文本大小实际上是相同的。

这里有一个小提琴:https://jsfiddle.net/ae1hdogr/

如果有人愿意尝试其他浏览器并更新小提琴,那么请这样做。我的主要目标是让这3个浏览器能够检测到人们在使用我的web应用程序时使用的缩放系数是否大于100%,并显示一个提示,建议使用更小的缩放系数。

在移动设备(Chrome for Android或Opera mobile)上,你可以通过window.visualViewport.scale来检测缩放。 https://developer.mozilla.org/en-US/docs/Web/API/Visual_Viewport_API

在Safari上检测:document.documentElement.clientWidth / window。innerWidth(如果设备上没有缩放则返回1)。

在Chrome

var ratio = (screen.availWidth / document.documentElement.clientWidth);
var zoomLevel = Number(ratio.toFixed(1).replace(".", "") + "0");

有它目前工作,但仍然需要由浏览器分开。 在Chrome(75)和Safari(11.1)上测试成功(目前还没有找到FF的方法)。 它还可以在视网膜显示器上获得正确的缩放值,并在调整大小事件时触发计算。

    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()
    };
  }

你可以使用Visual Viewport API:

window.visualViewport.scale;

它是标准的,在桌面和移动设备上都可以使用:浏览器支持。

试试这个

alert(Math.round(window.devicePixelRatio * 100));

这可以检测比例。

html代码:

<body id="blog">

js:

function scale(){
return Math.round(100/(d.getElementById('blog').offsetWidth/d.getElementById('blog').getBoundingClientRect().width))/100;
}

缩放因子和比例不能相互混淆。用户控制“缩放”; “scale”是一个CSS转换。然而,11年零10个月前,understack指出:

基本上我想知道DIV在100%缩放时的尺寸。

这个是这样的。我将其与@media查询一起使用,以检测JavaScript中的设备缩放,即360x720可能应用0.5缩放;720 x360, 0.75。

var d=document;

我使用了不同的方法,我创建了一个dom元素,高度和宽度固定为100px,位置固定,不透明度为0,基本上是一个隐藏元素。

然后我使用dom-to-image来捕获这个元素作为图像,这听起来可能有点过分,但我想要一个防弹的解决方案,我们已经在使用这个包了,然后验证输出图像宽度,如果它返回110,缩放是110%,这是非常准确的。

const ORIGINAL_ZOOM_SIZE = 100;
async function isValidateZoomLevel() {
    const base64Render = await domToImage({
      ref: hiddenElementReference,
    });
    const pixleRatio = Math.round(window.devicePixelRatio);
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = () => resolve(ORIGINAL_ZOOM_SIZE === img.width / pixleRatio && ORIGINAL_ZOOM_SIZE === (img.height / pixleRatio));
      img.onerror = reject;
      img.src = base64Render; 
    });
  }

我修复了下面的代码。

HTML:

<div class="mt-5"
        [ngStyle]="getStyles()">

TS:

getStyles() {
        const screenWidth = screen.width;
        const windowWidth = window.innerWidth;
        if (windowWidth != screenWidth) {
            const percentDifference = Math.ceil((screenWidth / windowWidth) * 100);
            if (percentDifference > 100) {
                this.bannerBackgroundImageSize = '20%, 74%';
            } else if (percentDifference === 100) {
                this.bannerBackgroundImageSize = '20%, 72%';
            } else if (percentDifference >= 90 && percentDifference <= 99) {
                this.bannerBackgroundImageSize = '25%, 70%';
            } else if (percentDifference >= 80 && percentDifference <= 89) {
                this.bannerBackgroundImageSize = '28%, 68%';
            } else if (percentDifference >= 75 && percentDifference <= 79) {
                this.bannerBackgroundImageSize = '29%, 67%';
            } else if (percentDifference >= 67 && percentDifference <= 74) {
                this.bannerBackgroundImageSize = '30%, 65%';
            } else if (percentDifference >= 50 && percentDifference <= 66) {
                this.bannerBackgroundImageSize = '30%, 61%';
            } else if (percentDifference < 50) {
                this.bannerBackgroundImageSize = '30%, 58%';
            }
        } else {
            this.bannerBackgroundImageSize = '20%, 72%';
        }
        const myStyles = {
            'background-size': this.bannerBackgroundImageSize,
        };
        return myStyles;
    }

我希望这将适用于所有缩放级别,它可以考虑与所有风格。