Highcharts - how to have a chart with dynamic heig

2020-02-08 05:19发布

I want to have a chart that resizes with the browser window, but the problem is that the height is fixed to 400px. This JSFiddle example has the same problem.

How can I do that? I tried using the chart.events.redraw event handler to resize the chart (using .setSize), but I guess it starts a never-ending loop (fire event handler, which calls setSize, which fires another event handler, etc.).

6条回答
看我几分像从前
2楼-- · 2020-02-08 05:26

What if you hooked the window resize event:

$(window).resize(function() 
{    
    chart.setSize(
       $(document).width(), 
       $(document).height()/2,
       false
    );   
});

See example fiddle here.

Highcharts API Reference : setSize().

查看更多
三岁会撩人
3楼-- · 2020-02-08 05:40

Remove the height will fix your problem because highchart is responsive by design if you adjust your screen it will also re-size.

查看更多
做个烂人
4楼-- · 2020-02-08 05:44

Another good option is, to pass a renderTo HTML reference. If it is a string, the element by that id is used. Otherwise you can do:

chart: {
    renderTo: document.getElementById('container')
},

or with jquery:

chart: {
    renderTo: $('#container')[0]
},

Further information can be found here: https://api.highcharts.com/highstock/chart.renderTo

查看更多
等我变得足够好
5楼-- · 2020-02-08 05:45

When using percentage, the height it relative to the width and will dynamically change along with it:

chart: {
    height: (9 / 16 * 100) + '%' // 16:9 ratio
},

JSFiddle Highcharts with percentage height

查看更多
狗以群分
6楼-- · 2020-02-08 05:50

Alternatively, you can directly use javascript's window.onresize

As example, my code (using scriptaculos) is :

window.onresize = function (){
    var w = $("form").getWidth() + "px";
    $('gfx').setStyle( { width : w } );
}

Where form is an html form on my webpage and gfx the highchart graphics.

查看更多
疯言疯语
7楼-- · 2020-02-08 05:53

Just don't set the height property in HighCharts and it will handle it dynamically for you so long as you set a height on the chart's containing element. It can be a fixed number or a even a percent if position is absolute.

Highcharts docs:

By default the height is calculated from the offset height of the containing element

Example: http://jsfiddle.net/wkkAd/149/

#container {
    height:100%;
    width:100%;
    position:absolute;
}
查看更多
登录 后发表回答