Window: resize event - Web APIs 编辑
The resize
event fires when the document view (window) has been resized.
Bubbles | No |
---|---|
Cancelable | No |
Interface | UIEvent |
Event handler property | onresize |
In some earlier browsers it was possible to register resize
event handlers on any HTML element. It is still possible to set onresize
attributes or use addEventListener()
to set a handler on any element. However, resize
events are only fired on the window
object (i.e. returned by document.defaultView
). Only handlers registered on the window
object will receive resize
events.
There is a proposal to allow all elements to be notified of resize changes. See Resize Observer to read the draft document, and GitHub issues to read the on-going discussions.
Examples
Window size logger
The following example reports the window size each time it is resized. Bear in mind that since the example is running in an <iframe>
, you'll need to actually get the <iframe>
to resize before you see an effect.
<p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>
const heightOutput = document.querySelector('#height');
const widthOutput = document.querySelector('#width');
function reportWindowSize() {
heightOutput.textContent = window.innerHeight;
widthOutput.textContent = window.innerWidth;
}
window.onresize = reportWindowSize;
addEventListener equivalent
You could set up the event handler using the addEventListener()
method:
window.addEventListener('resize', reportWindowSize);
Specifications
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论