Get a Google Chart image to fill the width of a DI

2019-07-17 08:26发布

问题:

I'm fetching some line charts using Google's Chart API and placing it in a DIV like this:

<div class="chart" style="display:block">
  <img src="http://chart.apis.google.com/chart?chs=620x40&cht=lfi&chco=0077CC&&chm=B,E6F2FA,0,0,0&chls=1,0,0&chd=t:27,25,25,25,25,27,100,31,25,36,25,25,39,25,31,25,25,25,26,26,25,25,28,25,25,100,28,27,31,25,27,27,29,25,27,26,26,25,26,26,35,33,34,25,26,25,36,25,26,37,33,33,37,37,39,25,25,25,25">
</div>

I have to pass the height and width of the chart image required and the Google Chart API renders it e.g. chs=620x40. I'd like the chart image to be the with of my parent div. I need to calculate the width and dynamically construct this chart URL so that I get a chart image of the right size. How can I do this?

(I'm not too bright with jQuery and I'm trying to avoid using some bloated libraries)

Thanks

回答1:

You can use the following JavaScript (with jQuery):

function sizeCharts(){
    $(".chart").each(function(){
        var w = $(this).width();
        var h = $(this).height(); // or just change this to var h = 40
        $("<img>").attr("src","http://chart.apis.google.com/chart?chs=" + \
            escape(w) + "x" + escape(h) + "&[etc]").appendTo(this);
    });
}
$(function(){
    sizeCharts();
    var shouldResize = true;
    $(window).bind("resize",function(){
        if(!shouldResize){
            return;
        }
        shouldResize = false;
        setTimeout(function(){
            sizeCharts();
            shouldResize = true;
        },1000);
    });
});

Replace [etc] with the rest of the url you wish to use. What happens in the above code is it will iterate through everything with the chart class in your page and puts the chart into it with the appropriate size.

If you use a liquid layout (i.e. your site resizes to fill a certain percentage of the screen), then you will also want to include the $(function(){ ... }) bit, which runs the same code when the page is resized. Note the use of timers here, otherwise the same chart will be reloaded for every pixel that the window is resized.