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

其他回答

这个答案是基于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(%)的缩放。

我修复了下面的代码。

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

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

你可以试试

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

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

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

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

这可以检测比例。

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;

我的同事和我使用了来自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);