天天看点

Echarts高度自适应

在开发数据大屏的时候,有需求要求echarts图表能自适应宽度和高度

实现原理:

  • 在监听页面大小变化的时候,先监听echarts父级元素的高度变化,计算出echarts的高度,然后再调用echarts的resize函数

关键代码

window.addEventListener("resize", () => {
  if (this.subItemsEcharts) {
    // 计算echarts高度
    this.setEchartsHeight('sub-items', 'sub-items-echarts', 30)
    this.subItemsEcharts.resize();
  }
});
           

完整代码

  • template部分
<div class="sub-items">
  <p class="title">
    <span class="name">分项能耗</span>
  </p>
  <div id="sub-items-echarts" style="width:100%;height:250px"></div>
</div>
           
  • mounted函数
window.addEventListener("resize", () => {
  if (this.subItemsEcharts) {
    // 计算echarts高度
    this.setEchartsHeight('sub-items', 'sub-items-echarts', 30)
    this.subItemsEcharts.resize();
  }
});
this.setEchartsHeight('sub-items', 'sub-items-echarts', 30)
           
  • setEchartsHeight.js部分
export default function setEchartsHeight(className, idName, num = 0) {
  // 父级高度
  let fatherHeight = document.getElementsByClassName(className)[0].offsetHeight
  // 计算echarts高度
  let echartsHeight = fatherHeight - num
  // 赋值
  document.getElementById(idName).style.height = echartsHeight + 'px'
}
           
  • style部分
.sub-items {
    width: 90%;
    height: 48%;
    margin: 2% auto;

    .title {
      width: 100%;
      height: 30px;
      line-height: 30px;

      .name {
        padding-left: 18px;
      }
    }
  }
           

如果本文对你有帮助,请点个赞吧!