功能
后台返回数据包含年,月和日,希望实现一个柱状图,当点击年数据时,下钻到月数据,点击月数据时,下钻到日数据。并包含返回功能。
思路
通过重绘图表的方式实现,实现思路如下:
1. 默认显示年数据
2. 当点击年数据柱子时,销毁图例,使用月数据重绘图表,下钻月数据类似
3. 增加一个按钮用来返回上层图表,使用相对定位定位在图表右上方
关键代码
本项目使用 jQuery + zui 实现,以下为关键代码:
index.html
<div class="boxall" style="height: 5rem" style="position: relative"> // 柱状图 <div id="BatteryReportChart" style="height: 4rem; margin-top: 20px"></div> // 返回标签 <button class="btn btn-info ring-button" id="onBack">Back</button></div>
css 文件:
.ring-button {position: absolute;right: 10%;top: 17%;}
index.js 文件:
// 全局变量,用于保存显示年、月还是日数据柱状图let dayMonthYear = "year";// 保存点击的年和月柱子数据,用于向后端请求数据和图表标题显示let globalYear = "";let globalMonth = "";// 点击返回按钮重绘表格$("#onBack").on("click", function () {if (dayMonthYear === "day") {dayMonthYear = "month";} else if (dayMonthYear === "month") {dayMonthYear = "year";}getChartData(dayMonthYear, globalYear, globalMonth);});function getChartData(dayMonthYear, globalYear, globalMonth) {// 该函数根据 dayMonthYear, globalYear, globalMonth 参数向后端请求数据并构造图表需要的 option// 具体实现过程省略BatteryReport(option);}// 销毁图表并重绘function BatteryReport(option) {// 销毁 ECharts 实例BatteryReportChart.dispose();BatteryReportChart = echarts.init(document.getElementById("BatteryReportChart"));BatteryReportChart.setOption(option);// 图表下钻BatteryReportChart.on("click", function (params) {if (dayMonthYear === "year") {dayMonthYear = "month";globalYear = params.name;} else if (dayMonthYear === "month") {dayMonthYear = "day";globalMonth = params.name;}getChartData(dayMonthYear, globalYear, globalMonth);});window.addEventListener("resize", function () {BatteryReportChart.resize();});}
References
[echarts 饼图下钻(下钻+可返回版本)](juejin.cn/post/709276…)
[ECharts 官网下钻一层的示例 ](echarts.apache.org/examples/zh…)
[数据可视化】echarts 数据下钻](www.bilibili.com/video/BV1FY…)