This is the 10th day of my participation in Gwen Challenge


As we all know, Windows has resize events that you can use to do special things. But this event is not supported for normal HTML elements. This creates problems for the adaptive scenarios of Echarts charts.

This article describes a few simple ways to solve the above problems.

1. Use ResizeObserver

Method of use

  1. Identify the element box that you want to listen on
  2. Determines that the onResize event is triggered when the size of the element being listened on changes
  3. Create a listener using ResizeObserver
const observer = new ResizeObserver(onResize).observe(box)
Copy the code
  1. Disconnect listening when a page or component is destroyed (optional)
observer.disconnect()
Copy the code

The instance

1. resizeobserver

Compatibility: All modern browsers support it

Caniuse.com/mdn-api_res…

2. Use relative + 100% + iframe/object

Method of use

  1. Set the listened element box to RELATIVE, or add a layer of element box around the element, set the outer element to RELATIVE, and set the inner element to fill box
  2. Create an iframe or object with the id of the element as helper. Set the property to absolute, width and height to 100%, fill box, and set visibility to Hidden. This is the step
  3. Determines that the onResize event is triggered when the size of the element being listened on changes
  4. Listen for the resize event of the window of an iframe or object and execute the onResize method in the event callback

The instance

2. iframe

Compatibility: IE is also supported

Under IE11, object is layered on top of the elements in the box, even if z-index is set to the lowest value. In this case it is recommended to transform out of the visible area, or just use iframe. Iframe does not have this problem.

3. Use the timer to query information periodically

Method of use

  1. Identify the element box that you want to listen on
  2. Determines that the onResize event is triggered when the size of the element being listened on changes
  3. Use the timer setInterval loop to query the size of the box and compare it to the value saved last time, and call onResize when not at the same time

The instance

3. raf

Compatibility: IE is also supported

But polling with setInterval triggers a redraw operation each time a size is fetched, which increases the performance strain on the browser.

conclusion

  • If you are considering support for modern browsers, ResizeObserver is the safest option, and even for unsupported browsers, Polyfill can be used
  • If you don’t want to use polyfill, you can use the second option, IFrame. The second option, however, has limitations on dom structures
  • Now that we have the above two methods, the timer method is not needed. Compared with the first two, it has a greater impact on performance