highcharts not responsive after reflow

2019-08-12 17:27发布

问题:

I am setting up a specialised Print button. The page is complicated and needs some pre-processing before being sent to window.print().

I have the Highcharts code working at this point. It correctly resizes the charts on the page, and then, post print, it sizes them back to their original size.

The problem is that from then on, the charts will not respond to Media Query changes. The site is Responsive, built on Bootstrap, so this is not a functional result.

How do I change the chart size, but leave it able to respond to Media Queries?

The code I am using is:

Setup Code

var saveChartContainerWidth = $('.highcharts-container').css('width');
var saveChartContainerWidthSVG = saveChartContainerWidth.slice(0, -2);

$('.highcharts-container').css('width', '690px');
$(Highcharts.charts).each(function(i,chart){
    var height = chart.renderTo.clientHeight; 
    var width = 690; // chart.renderTo.clientWidth; 
    chart.setSize(width, height);
    chart.reflow();
});

Post Print Teardown Code

    $('.highcharts-container').css('width', saveChartContainerWidth);
    $(Highcharts.charts).each(function(i,chart){
        var height = chart.renderTo.clientHeight; 
        var width = saveChartContainerWidthSVG;
        chart.setSize(width, height);
        chart.reflow();
    });

回答1:

With the help of @Ryan's link, and comments from a co-worker, I tried a number of solutions which, while not working, got me closer.

Having then a better idea of what to look for, I finally found this answer Highcharts + Bootstrap .table-responsive issue which provided a key ingredient.

The two keys are:

  1. Do not set the size on either the SVG itself, or the direct Highchart's container. (I set it on a containing Div one level higher.)

  2. Trigger a $(window).trigger("resize"); event.

This worked in all browsers tested (Firefox, Chrome, IE 9 - 11).

----------------- The Final Code -----------------------

// Setup

$('.chart-container').css('width', '690px');
$(window).trigger("resize");

// Teardown

$('.chart-container').css('width', '');
$(window).trigger("resize");


回答2:

Do this after setting the size will do the trick.

   window.onresize = () => {
     chart.setSize($('parentElement').offsetWidth, height)
     chart.reflow()
   }

Yet if you change the onresize function to something else, it might not work. So this is more like a quick solution, yet it works perfectly