移动端项目,做echarts的时候,legend图例太多,后台返回的,也不确定有多少个,产品说不要分页翻页的那种,所以只能通过计算legend的高度来自适应echarts
var chartDom = document.getElementById('chart');
var myChart = echarts.init(chartDom);
var dc = {
//计算echarts内部图例占用高度(不考虑富文本的情况) //5ms
getLegendHeight: function(index){
var height =0;
var charDOM = chartDom
var chart = myChart
var option = chart.getOption();
var legends = option.legend;
if(!legends||legends.length<=0) return 0;
index = parseInt(index);
if(isNaN(index)||index<0||index>=legend.length) index = 0;
var legend = legends[index];
console.log('legend',legend);
//主算法,将legend中的设置渲染为DOM元素,用dom元素的宽高来模拟legend组件在echarts内部的高度
var icongap = 5;//legend图形左右两边各有5个px的间隔
var left = legend.left,right = legend.right;
//计算legend组件的可用宽度
var chartWidth = legend.width||$(charDOM).width()-left-right;
//legend的padding
var padding = legend.padding || 0;
if($.isArray(padding)) padding = padding.join('px ')+'px';
else padding+='px';
//每个legend item之间的间隙(包括水平和垂直)
var itemGap = legend.itemGap;
//创建一个不可见的模拟盒子
var $legendbox = $('<div class="legend-simulate-box"></div>').css({
width: (chartWidth+itemGap) +'px',
padding: padding,
'line-height': '1',
'box-sizing': 'border-box',
overflow: 'hidden',
'position': 'absolute',
'z-index': '-1',
'opacity': '0',
'filter': 'alpha(opacity=0)',
'-ms-filter': 'alpha(opacity=0)'
}).appendTo('body');
//模拟绘制单个legend item
var itemHeight = legend.itemHeight,itemWidth = legend.itemWidth;
console.log('itemHeight',itemHeight);
if(itemHeight%2!=0) itemHeight++;
if(itemWidth%2!=0) itemWidth++;
var fontSize = legend.textStyle.fontSize || 14;
var fontWeight = legend.textStyle.fontWeight || 'normal';
$.each(legend.data,function(i,name){
var $icon = $('<span></span>').css({
display: 'inline-block',
padding: '0 '+icongap+'px',
'box-sizing': 'content-box',
'width': itemWidth+'px',
'height': itemHeight+'px'
});
var $item = $('<div></div>').css({
'display': 'inline-block',
'float': 'left',
'margin-right': itemGap+'px',
'margin-bottom': itemGap+'px',
'font-size': fontSize+'px',
'font-weight': fontWeight
}).append($icon).append(name).appendTo($legendbox);
});
//得到模拟高度
console.log('legendbox',$legendbox.innerHeight());
console.log('itemGap',itemGap);
height = $legendbox.innerHeight()-itemGap;
//善后工作
$legendbox.remove();
return height;
}
}
console.log('高度',dc.getLegendHeight());