<div id="main" style="width: 1632px;height:648px;"></div> let legendItems = ["折线1","折线2","折线3","折线4"]; let height = getLegendHeight(legendItems, "main", option.legend); /** * 模拟计算legend高度 */ function getLegendHeight(legendItems, chartElementId, legend) { let top = (typeof (legend.top) != "undefined" && legend.top != null) ? legend.top : 0; let left = (typeof (legend.left) != "undefined" && legend.left != null) ? legend.left : 0; //计算legend组件的可用宽度 let chartDOM = document.getElementById(chartElementId); let legendWidth = legend.width || parseFloat(document.defaultView.getComputedStyle(chartDOM).width) - left; //legend的padding let padding = (typeof (legend.padding) != "undefined" && legend.padding != null) ? legend.padding : 5; padding = (Array.isArray(padding) ? padding.join('px ') : padding) + 'px'; //模拟绘制legend item 默认间隙为10 高度为14 宽度为25 字体大小为12 let itemGap = (typeof (legend.itemGap) != "undefined" && legend.itemGap != null) ? legend.itemGap : 10; let itemWidth = (typeof (legend.itemWidth) != "undefined" && legend.itemWidth != null) ? legend.itemWidth : 25; let itemHeight = (typeof (legend.itemHeight) != "undefined" && legend.itemHeight != null) ? legend.itemHeight : 14; let fontSize = (typeof (legend.textStyle.fontSize) != "undefined" && legend.textStyle.fontSize != null) ? legend.textStyle.fontSize : 12; let fontWeight = (typeof (legend.textStyle.fontWeight) != "undefined" && legend.textStyle.fontWeight != null) ? legend.textStyle.fontWeight : 'normal'; //创建一个不可见的模拟盒子 let legendHtml = '<div id="legendBox" style="position: absolute; display: flex; flex-wrap: wrap; width: ' + (legendWidth + itemGap) + 'px; margin-left: ' + left + 'px; margin-top: ' + top + 'px; padding: ' + padding + ';">'; for (let i = 0; i < legendItems.length; i++) { legendHtml += '<div style="display: inline-flex; margin-right: ' + itemGap + 'px; margin-bottom: ' + itemGap + 'px; font-size: ' + fontSize + 'px; font-weight: ' + fontWeight + '; line-height: 1;"><span style=" margin-right: 5px; width: ' + itemWidth + 'px; height: ' + itemHeight + 'px; background-color: #f25555; border-radius: 4px;"></span>' + legendItems[i] + '</div>'; } legendHtml += '</div>'; //创建一个不可见的模拟盒子 chartDOM.insertAdjacentHTML('afterbegin', legendHtml); let legendBoxDOM = document.getElementById('legendBox'); //得到模拟高度 let height = parseFloat(document.defaultView.getComputedStyle(legendBoxDOM).height); //更改图表div高度 chartDOM.style.height = (parseFloat(chartDOMStyle.height) + height) + 'px'; //善后工作 legendBoxDOM.remove(); return height; };
echarts计算legend高度
于 2023-06-08 15:00:18 首次发布