如何在所有现代浏览器中检测页面缩放级别?虽然这篇文章讲述了如何在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>

当前回答

在移动设备(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)。

其他回答

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

编辑(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>

我修复了下面的代码。

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

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

基本上,我们有:

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

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

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

在Chrome

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

在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中不存在缩放,所以没有必要检查缩放。