google visualization chart, size in percentage

2019-02-21 10:53发布

How do you set the size of a google chart in percentage : I have this in the html:

<div id="chart_div" width="90%" height="20%"></div>

and no width nor height in the options in the js.

But the chart size doesn't adapt to the viewport.

Thanks

5条回答
The star\"
2楼-- · 2019-02-21 11:32

By multiplying with appropriate factor to $(window).width() or $(window).height() in the chart options

var options = {
        width: $(window).width(),
        height: $(window).height()*0.75
};
查看更多
走好不送
3楼-- · 2019-02-21 11:37

First, use styles to set your dimensions, not attributes:

<div id="chart_div" style="width: 90%; height: 20%;"></div>

The chart will draw to the size of the div by default, but the charts are not responsive. You have to hook a "resize" event handler to the window (or other element if you are resizing within a window) that redraws the chart:

function resizeChart () {
    chart.draw(data, options);
}
if (document.addEventListener) {
    window.addEventListener('resize', resizeChart);
}
else if (document.attachEvent) {
    window.attachEvent('onresize', resizeChart);
}
else {
    window.resize = resizeChart;
}
查看更多
混吃等死
4楼-- · 2019-02-21 11:39

Please Remove the width and the height properties from the options in the scripts and then add the following style to your page

<style>
    .chart {
        width: 100%;
        min-height: 450px;
    }

    .row {
        margin: 0 !important;
    }
</style>
查看更多
等我变得足够好
5楼-- · 2019-02-21 11:43

Google recommend that you style, like the answer above, with correct CSS and this makes a less-glitchy Chart. However, you can size it up in Javascript...
https://developers.google.com/chart/interactive/docs/basic_customizing_chart
So, for the options when you draw the chart (using chart.draw(data, options) as above)...

var options = {
    width:400,
    height:300
}

A good fiddle for a responsive design is here...
http://jsfiddle.net/toddlevy/pyAz5/

查看更多
女痞
6楼-- · 2019-02-21 11:43
$(window).resize(function(){
    var container = document.getElementById("chart_div").firstChild.firstChild;
    container.style.width = "100%";

    chart.draw(data, options);
});
查看更多
登录 后发表回答