在我们开发过程中,根据项目需求,需要将echarts图表先隐藏,然后点击按钮让它再显示出来。
但是再显示时,图表出现了问题,它变得特别小,根本不能用
原因:Echarts 图表是根据你定义的div 的样式来确定图表的大小,当图表隐藏时,Echarts会找不到div的宽和高,再次显示时它会给自己一个非常小的默认宽高值,所以在隐藏显示后会发现它变得非常非常的小。
解决办法:
1.在完成绘画echarts后添加代码:$(window).resize(myChart.resize);
var dom = document.getElementById("jindu"); var myChart = echarts.init(dom); option = { ...... } myChart.setOption(option); $(window).resize(myChart.resize);
2.在图表要显示的地方添加代码:$(window).trigger(‘resize');【(gmFlag 定义在全局,渲染的数据图表的方法加 gmFlag = 1;】
if(gmFlag == 1){ $(".allscore").show(); $(window).trigger('resize'); }
这样来回切换的时候图表的大小就不会改变了,如图
附上完整代码:
// 图表 var myChart = echarts.init(document.getElementById('sale-chart')); myChart.setOption({ color: ['#3398DB'], toolbox: { right: 15, feature: { magicType: { type: ['line', 'bar'] } } }, tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: '{b}<br />{c}辆' }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, dataset: { source: [] }, xAxis: [{ type: 'category', axisTick: { alignWithLabel: true }, axisLine: { show: false }, axisLabel: { fontSize: 10, color: '#8e8e8e' }, axisTick: { show: false }, data: [] }], yAxis: [{ type: 'value', nameTextStyle: { fontSize: 10 }, axisLine: { show: false }, splitLine: { show: false, lineStyle: { color: ['rgba(100,100,100,0.1)'] } }, axisTick: { show: false }, axisLabel: { show: false } }], series: [{ name: '销量', type: 'bar', barWidth: '30%', label: { show: true, position: 'top', color: '#8e8e8e' }, itemStyle: { emphasis: { barBorderRadius: 100 }, normal: { barBorderRadius: 100, color: new echarts.graphic.LinearGradient( 0, 1, 0, 0, [{ offset: 0, color: '#007eff' }, { offset: 1, color: '#00adff' } ] ) } }, data: [] }] }); $(window).resize(myChart.resize); var gmFlag = 0; function showCategory(type, obj) { if (type == 'cx') { $(".switch-btn,.model-list-wrap").show(); $("#sale_wrap,#kb_wrap,#cjj_wrap,#by_wrap").hide(); $('.category-items').removeClass('category-act'); $(obj).addClass('category-act'); } else { $('.category-items').removeClass('category-act'); $(obj).addClass('category-act'); $("#sale_wrap").show(); // 图表 if (gmFlag == 1) { $("#sale-chart").show(); $(window).trigger('resize'); } $(".switch-btn,.model-list-wrap,#kb_wrap,#cjj_wrap,#by_wrap").hide(); } }
参考链接:https://www.jb51.net/article/191133.htm