JavaScript 如何检测窗口大小是否改变
当浏览器窗口的大小发生变化时,会触发窗口调整大小事件。我们可以通过两种方式监听窗口调整大小事件:
- 使用 onresize 事件
- 使用 Resize Observer API
方法1:使用resize事件
我们可以给body元素添加事件监听器,每次窗口大小调整时触发。
示例: 以下示例展示了上述方法的使用。
<!DOCTYPE html>
<html>
<head>
<title>
How to detect and resize
the window size
</title>
<style>
body {
text-align: center;
}
h1 {
color:green;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h3>
Resizing the screen size and display its
<br>corresponding width and height
</h3>
<div id="height">Height: <span></span></div>
<div id="width">Width: <span></span></div>
<script>
const height = document.querySelector("#height span");
const width = document.querySelector("#width span");
// Insert values on load of page
window.onload = function() {
height.innerHTML = window.innerHeight;
width.innerHTML = window.innerWidth;
};
// Change values when window is resized
window.onresize = function() {
// Setting the current height & width
// to the elements
height.innerHTML = window.innerHeight;
width.innerHTML = window.innerWidth;
};
</script>
</body>
</html>
HTML
输出:
方法2:使用ResizeObserver API
我们可以使用最新的ResizeObserver API来监听窗口调整大小事件。这个API并不完全支持。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to detect and resize
the window size
</title>
<style>
body {
text-align: center;
}
h1 {
color:green;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h3>
Resizing the screen size and display its
<br>corresponding width and height
</h3>
<div id="height">Height: <span></span></div>
<div id="width">Width: <span></span></div>
<script>
const body = document.getElementsByTagName("body")[0];
const height = document.querySelector("#height span");
const width = document.querySelector("#width span");
// Initialize resize observer object
let resizeObserver = new ResizeObserver(() => {
// Set the current height and width
// to the element
height.innerHTML = window.innerHeight;
width.innerHTML = window.innerWidth;
});
// Add a listener to body
resizeObserver.observe(body);
</script>
</body>
</html>
HTML
输出: