ResizeObserver 构造函数创建新 ResizeObserver object, which can be used to report changes to the content or border box of an 元素 or the bounding box of an SVGElement .

句法

var ResizeObserver = new ResizeObserver(callback)
					

参数

callback
The function called whenever an observed resize occurs. The function is called with two parameters:
entries
An array of ResizeObserverEntry objects that can be used to access the new dimensions of the element after each change.
observer
A reference to the ResizeObserver itself, so it will definitely be accessible from inside the callback, should you need it. This could be used for example to automatically unobserve the observer when a certain condition is reached, but you can omit it if you don't need it.

The callback will generally follow a pattern along the lines of:

function(entries, observer) {
  for (let entry of entries) {
    // Do something to each entry
    // and possibly something to the observer itself
  }
}
								

范例

The following snippet is taken from the resize-observer-text.html ( see source ) example:

const resizeObserver = new ResizeObserver(entries => {
  for (let entry of entries) {
    if(entry.contentBoxSize) {
      h1Elem.style.fontSize = Math.max(1.5, entry.contentBoxSize.inlineSize/200) + 'rem';
      pElem.style.fontSize = Math.max(1, entry.contentBoxSize.inlineSize/600) + 'rem';
    } else {
      h1Elem.style.fontSize = Math.max(1.5, entry.contentRect.width/200) + 'rem';
      pElem.style.fontSize = Math.max(1, entry.contentRect.width/600) + 'rem';
    }
  }
});
resizeObserver.observe(divElem);
							

规范

规范 状态 注释
重置大小观测器
The definition of 'ResizeObserver' in that specification.
编者草案 初始定义。

浏览器兼容性

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
ResizeObserver() 构造函数 Chrome 64 Edge 79 Firefox 69 IE No Opera 51 Safari 13.1 WebView Android 64 Chrome Android 64 Firefox Android No Opera Android 47 Safari iOS 13.4 Samsung Internet Android 9.0

图例

完整支持

完整支持

不支持

不支持

元数据

  • 最后修改:
  1. 重置尺寸观测器 API
  2. ResizeObserver
  3. 构造函数
    1. ResizeObserver()
  4. 方法
    1. disconnect()
    2. observe()
    3. unobserve()
  5. Related pages for Resize Observer API
    1. ResizeObserverEntry