我們的志工尚未將本文翻譯為 正體中文 (繁體) 版本。加入我們,幫忙翻譯!
您也可以閱讀本文的 English (US) 版本。

The resize event fires when the document view (window) has been resized.

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 (sent to) the window object (document.defaultView). Only handlers registered on the window object will receive events.

There is a new proposal (2017) 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.

General info

Interface UIEvent
Bubbles No
Cancelable No
Targets Document.defaultView (window)
Default Action None

Properties

Property Type Description
target Read only EventTarget The event target (the topmost target in the DOM tree).
type Read only DOMString The type of event.
bubbles Read only Boolean Whether the event normally bubbles or not.
cancelable Read only Boolean Whether the event is cancellable or not.
view Read only WindowProxy Document.defaultView (window of the document)
detail Read only long (float) 0.

Examples

You can register an event handler for the resize event using either window.onresize or window.addEventListener('resize', ...).

Since resize events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using setTimeout() or requestAnimationFrame(). Below, you can find an example using setTimeout().

setTimeout

const delay = 100;  // Your delay here

const originalResize = evt => {
  console.log(evt);  // Your resize function here
};


(() => {
  resizeTaskId = null;

  window.addEventListener('resize', evt => {
    if (resizeTaskId !== null) {
      clearTimeout(resizeTaskId);
    }

    resizeTaskId = setTimeout(() => {
      resizeTaskId = null;
      originalResize(evt);
    }, delay);
  });
})();

Specifications

See also