JavaScript 如何在所有现代浏览器中检测页面缩放级别

JavaScript 如何在所有现代浏览器中检测页面缩放级别

在本文中,我们将讨论如何在网页上找到当前的缩放量。

方法1:使用 outerWidth 和 innerWidth 属性: 在像Chrome和Microsoft Edge这样的webkit浏览器中,检测缩放级别更容易。这种方法使用了JavaScript的内置函数outerWidth和innerWidth属性。首先,将outerWidth减去10,以考虑滚动条的影响,然后将结果除以innerWidth,得到缩放级别。

注意: 缩放量可能不完全等于浏览器显示的缩放量。可以通过四舍五入来解决这个问题。

语法:

let zoom = (( window.outerWidth - 10 ) / window.innerWidth) * 100;
JavaScript

示例: 此示例展示了上述解释的方法的使用。

<body> 
    <h1 style="color: green"> 
        GeeksforGeeks 
    </h1> 
      
    <b> 
        Zoom in or out of the page to 
        get the current zoom value 
    </b> 
      
    <p>Current Zoom Level: 
        <span class="output"> 
        </span> 
    </p> 
      
    <script> 
        window.addEventListener( 
            "resize", getSizes, false); 
          
        let out = document.querySelector(".output"); 
          
        function getSizes() { 
            let zoom = ((window.outerWidth - 10) 
                / window.innerWidth) * 100; 
                  
            out.textContent = zoom; 
        } 
    </script> 
</body>
JavaScript

输出:

JavaScript 如何在所有现代浏览器中检测页面缩放级别

方法2:使用 clientWidth 和 clientHeight 属性: 由于在多个浏览器中无法找到缩放的数量,可以通过查找网站的尺寸来执行操作。这种方法使用JavaScript的内置函数 clientWidth 和 clientHeight 属性。

语法:

let zoom = body.clientWidth + "px x " + body.clientHeight + "px";
JavaScript

示例: 该示例展示了上述解释的方法的用途。

<head> 
    <style> 
        /* Set the body to occupy the 
           whole browser window 
           when there is less content */ 
        body { 
            height: 100vh; 
            margin: 0; 
        } 
    </style> 
</head> 
<body> 
    <h1 style="color: green"> 
        GeeksforGeeks 
    </h1> 
      
    <b> 
        Zoom in or out of the page to 
        get the current zoom value 
    </b> 
      
    <p> 
        Current Zoom Level in pixels: 
        <span class="output"> 
        </span> 
    </p> 
      
    <script> 
        window.addEventListener( 
                "resize", getSizes, false); 
                  
        let out = document.querySelector(".output"); 
          
        function getSizes() { 
            let body = document.body; 
            let zoom = body.clientWidth + "px x " + 
                body.clientHeight + "px"; 
            out.textContent = zoom; 
        } 
    </script> 
</body>
HTML

输出:

JavaScript 如何在所有现代浏览器中检测页面缩放级别

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册