Echarts implements chart adaptive screen resolution

One: Introduction

When working on a project before, it is necessary to realize that the echarts chart changes with the size of the browser window. echarts itself provides a resize() method, and then we need to use a function to monitor the browser window. Initially, I chose the window.onresize method. It can be realized when there is only one chart on the page, but when there are multiple charts on the page, window.onresize will be overwritten and cause failure. Finally, I chose the window.addEventListener() method to solve this problem

Two: The problem of window.onresize

This is because onresize itself is a callback, when a change occurs, the previous method will be overwritten

Three: Application of window.addEventListener()

The EventTarget.addEventListener() method registers the specified listener to the EventTarget, and when the object triggers the specified event, the specified callback function will be executed. The event target can be an element Element, Document, and Window on a document , or any object that supports events (such as XMLHttpRequest)

grammar:

addEventListener(event, function, useCapture)

  • The parameter event is required, indicating the event to be monitored, such as click, resize, etc., without the prefix on.
  • The parameter function is required, indicating the function to be called after the event is triggered, which can be an externally defined function or an anonymous function. without parameters.
  • The parameter useCapture is optional, fill in true or false to describe whether the event is a bubbling or a capture trigger, true means capture, and the default false means bubbling.
     

Code:

window.addEventListener('resize', this.screenAdapter)

screenAdapter(){
    this.chartInstance.resize()
}

Among them, screenAdapter is the function called after the resize event is triggered. At the same time, don't forget to use window.removeEventListener to remove the listener

Guess you like

Origin blog.csdn.net/qq_42691298/article/details/129690567