简体   繁体   English

使谷歌图表响应

[英]Make google chart responsive

Im using google charts in a project but im having a hard time to make them responsive.我在一个项目中使用谷歌图表,但我很难让它们做出响应。

Iǘe seen other examples on responsive charts but I cant seem to get it to work in my case.我在响应式图表上看到了其他例子,但我似乎无法让它在我的情况下工作。 All my charts gets rendered and after that their sizes do not change.我所有的图表都被渲染,之后它们的大小不会改变。

If someone can make this chart responsive id appreciate it.如果有人可以使此图表具有响应性,我将不胜感激。 Thank you:谢谢:

function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Year');
    data.addColumn('number', 'Revenue');
    data.addColumn('number', 'Average Revenue');
    data.addRows([
      ['2004', 1000, 630],
      ['2005', 1170, 630],
      ['2006', 660, 630],
      ['2007', 1030, 630]
    ]);

    var options = {
      title: 'Revenue by Year',
      seriesType: "bars",
      series: {1: {type: "line"}},  
      vAxis: {title: 'Year',
              titleTextStyle:{color: 'red'}},
        colors:['red','black']
    };

    var chart = new google.visualization.ComboChart(document.getElementById('chart'));
    chart.draw(data, options);
}

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

Fiddle for the chart: Fiddle图表的小提琴小提琴

If it could take up a percentage width of a parent it would be great如果它可以占据父级的百分比宽度,那就太好了

The solution was already given online elsewhere.其他地方网上已经给出了解决方案。

You need to call your drawChart() function whenever the window is resized to get the desired behaviour.每当调整窗口大小以获得所需的行为时,您都需要调用 drawChart() 函数。 The website flopreynat.com exactly describes this problem and solution ( codepen ).网站flopreynat.com准确地描述了这个问题和解决方案 ( codepen )。 It describes how this can be done using JQuery:它描述了如何使用 JQuery 完成此操作:

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

Using just Javascript, this answer on Stack Exchange by Sohnee describes how to trigger functions upon a resize event:仅使用 Javascript, Sohnee 在 Stack Exchange 上的这个答案描述了如何在调整大小事件时触发函数:

window.onresize = doALoadOfStuff;

function doALoadOfStuff() {
    //do a load of stuff
}

All credit to both authors of the links above.以上链接均归功于两位作者。

Add width_units to your option block:将 width_units 添加到您的选项块:

var options = {
    width: 80,
    width_units: '%'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM