在echarts中,不设置高度,图表无法渲染;若设置固定高度,当柱状图数据过多时轴文本标签会自动隐藏且数据挤压,用户的体验差。通过给容器设置自适应高度,然后通过getDom()的方法解决此问题。
var myChart = echarts.init(document.getElementById("container")); var option = { yAxis: { type: 'category', interval: 0, data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Thu', 'Fri', 'Sat', 'Sun','Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Thu', 'Fri', 'Sat', 'Sun'] }, xAxis: { type: 'value' }, series: [{ data: [120, 200, 150, 80, 70, 110, 130, 80, 70, 110, 130,120, 200, 150, 80, 70, 110, 130, 80, 70, 110, 130], type: 'bar', }] } myChart.setOption(option); //柱状图y轴的长度 option.yAxis.data.length var autoHeight = option.yAxis.data.length * 50 + 150; myChart.getDom().style.height = this.autoHeight + "px"; myChart.getDom().childNodes[0].style.height = this.autoHeight + "px"; myChart.getDom().childNodes[0].childNodes[0].setAttribute("height", this.autoHeight); myChart.getDom().childNodes[0].childNodes[0].style.height = this.autoHeight + "px"; myChart.getDom().childNodes[0].childNodes[0].style.background = "rgba(0,0,0,0.5)"; //根据窗口的大小变动图表 myChart.resize();
Done!