之前一直没弄清楚echarts到底是怎么自适应窗口大小的,最近做H5项目中忽然找到原因了。
<div id="myChart" style="height: 300px;"></div>
<script src="../js/echarts.min.js"></script>
<script type="text/javascript">
/*------------- 绘制图表-------------------*/
var HChart = echarts.init(document.getElementById('myChart'))
var option = {
tooltip: {},
legend: {
// x: 'right',
data: ['2019', '2018']
},
grid: {
left: '5%', // 图表距边框的距离
right: '0%'
},
xAxis: {
data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
},
yAxis: {},
series: [{
barWidth: 20,
name: '2019',
type: 'bar',
data: [5, 20, 36, 10, 10, 20, 36, 10, 12, 20, 23, 25],
itemStyle: {
normal: {
// 这里用函数控制柱子颜色,定义一个list,然后根据所以取得不同的值
color: function (params) {
var colorList = [
'#3b7fd5']
return colorList[params.dataIndex]
}
}
}
},
{
barWidth: 20,
name: '2018',
type: 'bar',
data: [5, 20, 46, 15, 16, 30, 46, 8, 10, 12, 20, 23],
itemStyle: {
normal: {
// 这里用函数控制柱子颜色,定义一个list,然后根据所以取得不同的值
color: function (params) {
var colorList = [
'#e4e4e4']
return colorList[params.dataIndex]
}
}
}
}]
}
//动态获取窗口尺寸以便重置图表尺寸,用于使chart自适应高度和宽度,通过窗体高宽计算容器高宽
window.onresize = HChart.resize;
HChart.setOption(option);
//动态获取当前窗口的宽度
// $(window).resize(function(){
// var Width = $(window).width();
// })
//重置图表的尺寸
// myChart.resize(function(){
// chartsContainer.style.width = chartsContainer.offsetWidth + 'px'
// })
</script>