2023.11.4 将echart变成响应式布局
echart并不会自动随着窗口大小的变化进行调整,可以调用resize()方法持续监听窗口大小的变化事件,实现响应式布局。
// 监听窗口大小变化事件
window.addEventListener('resize', function() {
// 调用 resize 方法重新渲染图表
chart.resize();
});
完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Responsive ECharts Bar Chart</title>
<!-- 引入 ECharts 的 JavaScript 文件 -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.2.2/dist/echarts.min.js"></script>
<style>
/* 设置容器的宽度和高度 */
/* begin响应式布局 */
/* 大屏幕的PC端 */
@media screen and (min-width: 1200px){
#chartContainer {
width: 1300px;
height: 400px;
}
}
/* 小屏幕的PC端 */
@media screen and (min-width: 992px) and (max-width: 1200px){
#chartContainer {
width: 1000px;
height: 400px;
}
}
/* 平板 */
@media screen and (min-width: 768px) and (max-width: 992px){
#chartContainer {
width: 800px;
height: 300px;
}
}
/* 手机端 */
@media screen and (max-width: 768px){
#chartContainer {
width: 100%;
height: 300px;
}
}
/* end响应式布局 */
</style>
</head>
<body>
<div id="chartContainer"></div>
<script>
// 创建图表对象
var chart = echarts.init(document.getElementById('chartContainer'));
// 图表配置项
var option = {
title: {
text: '柱状图示例'
},
xAxis: {
type: 'category',
data: ['A', 'B', 'C', 'D', 'E']
},
yAxis: {
type: 'value'
},
series: [{
data: [20, 40, 15, 25, 30],
type: 'bar'
}]
};
// 设置图表配置项并渲染图表
chart.setOption(option);
// 监听窗口大小变化事件
window.addEventListener('resize', function() {
// 调用 resize 方法重新渲染图表
chart.resize();
});
</script>
</body>
</html>