Google图表 - 响应问题 - 动态调整大小

时间:2017-11-16 16:02:48

标签: javascript html google-visualization responsive google-chartwrapper

我正在努力让我的Google Column Material Chart响应,但它似乎对我来说有些不稳定,并且根本无法正常工作。任何人都可以帮助我顺利完成这个流程

图表仅在加载页面时以该格式显示。当浏览器窗口宽度发生变化时,它不会动态调整大小。

的jsfiddle https://jsfiddle.net/rbla/Le8g0sw0/8/

HTML

<div id="chart">
    <div id="chart_div"></div>
</div>

CSS

#chart {
   border:5px solid #AAA;
   width: 80%; 
   min-height: 450px;
}

JS

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script>

  google.charts.load('current', {'packages':['bar']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses', 'Profit'],
      ['2014', 1000, 400, 200],
      ['2015', 1170, 460, 250],
      ['2016', 660, 1120, 300],
      ['2017', 1030, 540, 350]
    ]);

    var options = {
      chart: {
        title: 'Company Performance',
        subtitle: 'Sales, Expenses, and Profit: 2014-2017',
      },
      bars: 'vertical',
      vAxis: {format: 'decimal'},
      height: 400,
      colors: ['#1b9e77', '#d95f02', '#7570b3']
    };

    var chart = new google.charts.Bar(document.getElementById('chart_div'));

    chart.draw(data, google.charts.Bar.convertOptions(options));



  }

     // REFLOW
    $(window).resize(function(){
        drawChart();
    });

2 个答案:

答案 0 :(得分:2)

在小提琴中,你正在使用JQuery来监听窗口调整大小......

T6

然而,JQuery不包括在内......

使用 $(window).resize(function(){ drawChart(); }); 代替,或者包含对JQuery的引用,
请参阅以下工作代码段...

addEventListener
google.charts.load('current', {
  packages: ['bar']
}).then(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Year', 'Sales', 'Expenses', 'Profit'],
    ['2014', 1000, 400, 200],
    ['2015', 1170, 460, 250],
    ['2016', 660, 1120, 300],
    ['2017', 1030, 540, 350]
  ]);

  var options = {
    chart: {
      title: 'Company Performance',
      subtitle: 'Sales, Expenses, and Profit: 2014-2017',
    },
    bars: 'vertical',
    vAxis: {format: 'decimal'},
    height: 400,
    colors: ['#1b9e77', '#d95f02', '#7570b3']
  };

  var chart = new google.charts.Bar(document.getElementById('chart_div'));
  chart.draw(data, google.charts.Bar.convertOptions(options));
  window.addEventListener('resize', drawChart, false);
}
#chart {
  border: 5px solid #AAA;
  min-height: 450px;
}

答案 1 :(得分:0)

将宽度从80%更改为100%,如下例所示:

#chart {
    border: 5px solid #AAA;
    width: 100%;
    min-height: 450px;
}