JavaScript 如何在所有现代浏览器中检测页面缩放级别
在本文中,我们将讨论如何在网页上找到当前的缩放量。
方法1:使用 outerWidth 和 innerWidth 属性: 在像Chrome和Microsoft Edge这样的webkit浏览器中,检测缩放级别更容易。这种方法使用了JavaScript的内置函数outerWidth和innerWidth属性。首先,将outerWidth减去10,以考虑滚动条的影响,然后将结果除以innerWidth,得到缩放级别。
注意: 缩放量可能不完全等于浏览器显示的缩放量。可以通过四舍五入来解决这个问题。
语法:
let zoom = (( window.outerWidth - 10 ) / window.innerWidth) * 100;
示例: 此示例展示了上述解释的方法的使用。
<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>
输出:
方法2:使用 clientWidth 和 clientHeight 属性: 由于在多个浏览器中无法找到缩放的数量,可以通过查找网站的尺寸来执行操作。这种方法使用JavaScript的内置函数 clientWidth 和 clientHeight 属性。
语法:
let zoom = body.clientWidth + "px x " + body.clientHeight + "px";
示例: 该示例展示了上述解释的方法的用途。
<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>
输出: