CSS 在窗口调整大小之前,响应式 Highcharts 无法正确调整大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16182935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:37:20  来源:igfitidea点击:

Responsive Highcharts not sizing correctly until window resize

javascriptcsshighchartszurb-foundationdynamic-resizing

提问by user2313761

I'm using Highcharts within Zurb's Foundation framework for a class project. I have three charts within a section tab. One is within a 12-column div, the other two are on the same row within 6-column divs.

我在 Zurb 的 Foundation 框架中使用 Highcharts 进行课堂项目。我在一个部分选项卡中有三个图表。一个位于 12 列 div 内,另外两个位于 6 列 div 内的同一行。

When the page loads, the featured chart does not take up the available width of the 12 columns, and the two smaller charts overflow their 6 columns. However, when the window is resized or I try to investigate using Inspect element, the charts immediately snap into the correct dimensions. This behavior occurs in Chrome, FF, and IE.

当页面加载时,特色图表没有占用 12 列的可用宽度,两个较小的图表溢出了它们的 6 列。但是,当调整窗口大小或我尝试使用 Inspect 元素进行调查时,图表会立即对齐到正确的尺寸。此行为发生在 Chrome、FF 和 IE 中。

I realize I could set a specific width, but I'd really like to take advantage of Foundation and keep them responsive.

我意识到我可以设置一个特定的宽度,但我真的很想利用 Foundation 并让它们保持响应。

I've tweaked the CSS and Highcharts initializations, but I'm stumped. Has anyone else experienced this issue? Can anyone see what I'm missing?

我已经调整了 CSS 和 Highcharts 初始化,但我很难过。有没有其他人遇到过这个问题?谁能看到我错过了什么?

Here's an excerpt from my HTML:

这是我的 HTML 的摘录:

<div class="row">
<div class="twelve columns">
    <!--begin tabs below--> 
    <div class="section-container tabs" data-section="tabs">
      <section>
        <p class="title" data-section-title><a href="#">Heart Disease</a></p>
        <div class="content" data-section-content id="heart">

            <div class="row feature-chart">
                <div class="large-12 columns">
                    <div id="heartTimeline-container">
                    <div id="heartTimeline"></div>
                    </div>
                </div> <!--close 12 columns-->
            </div> <!--close row-->
            <div class="row small-charts">
                <div class="large-6 columns">
                    <div id="heartDemo"></div>
                </div>
                <!--close 6-->
                <div class="large-6 columns">
                    <div id="heartStages"></div>
                </div>
                <!--close 6-->
            </div>
            <!--end row-->
        </div>
      </section>
   </div>
   </div>
   <!--end twelve columns-->

Here's the Highcharts js:

这是 Highcharts js:

$(function () {
    Highcharts.setOptions({
        colors: ['#1A1A1A', '#455D78', '#BDCCD4', '#999999', '#B3B3B3', '#F2F2F2']
    });
    $('#heartTimeline').highcharts({
        chart: {
            type: 'area'
        },
        title: {
            text: 'Heart Disease Death Rates in the U.S.from 1980-2010'
        },
        subtitle: {
            text: 'Source: <a href="http://www.mdch.state.mi.us/pha/osr/deaths/Heartdx.asp">'+ 
                        'Michigan Department of Community Health</a>'
        },
        xAxis: {
            labels: {
                formatter: function() {
                    return this.value; // clean, unformatted number for year
                }
            }
        },
        yAxis: {
            title: {
                text: 'Heart Disease Death Rate Per 100,000 People'
            },
            labels: {
                formatter: function() {
                    return this.value / 1 +'k';
                }
            }
        },
        tooltip: {
            pointFormat: '{series.name} produced <b>{point.y:,.0f}</b><br/>deaths per hundred thousand people in {point.x}'
        },
        plotOptions: {
            area: {
                pointStart: 1980,
                marker: {
                    enabled: false,
                    symbol: 'circle',
                    radius: 2,
                    states: {
                        hover: {
                            enabled: true
                        }
                    }
                }
            }
        },
        series: [{
            name: 'Heart Disease',
            data: [412.1, 397, 389, 388, 378, 375, 365.1, 355.9, 352.5, 332, 321.8, 313.8, 306.1, 309.9, 299.7, 296.3, 288.3, 280.4, 272.4, 267.8, 257.9, 247.8, 240.8, 232.3, 217, 211.1, 200.2, 190.9, 186.5, 180.1, 178.5]
        }, ]
    });
});
$(function () {
    $('#heartDemo').highcharts({
        chart: {
            zoomType: 'xy'
        },
        title: {
            text: 'Most Prevelant Causes and Effects of Heart Disease 2013'
        },
        subtitle: {
            text: 'Source: http://circ.ahajournals.org (The American Heart Association)'
        },
        xAxis: [{
            categories: ['Smoking', 'Obesity (BMI > 25 kg) ', 'Total cholesterol > 200 mg)', 'High Blood Pressure', 'Diabetes Mellitus', 'Prediabetes', 'Total Cardiovascular Disease', 'Stroke', 'Coronary Heart Disease', 'Heart Failure'],
            labels: {
                rotation: -90,
                align:'right'
            }
        }],
        yAxis: [{ // Primary yAxis
            labels: {
                formatter: function() {
                    return this.value +'%';
                },
                style: {
                    color: '#000000'
                }
            },
            title: {
                text: 'Men',
                style: {
                    color: '#BDCCD4'
                }
            },
            opposite: true

        }, { // Secondary yAxis
            gridLineWidth: 0,
            title: {
                text: 'Both Sexes',
                style: {
                    color: '#455D78'
                }
            },
            labels: {
                formatter: function() {
                    return this.value +' %';
                },
                style: {
                    color: '#4572A7'
                }
            }

        }, { // Tertiary yAxis
            gridLineWidth: 0,
            title: {
                text: 'Women',
                style: {
                    color: '#AA4643'
                }
            },
            labels: {
                formatter: function() {
                    return this.value +' %';
                },
                style: {
                    color: '#AA4643'
                }
            },
            opposite: true
        }],
        tooltip: {
            shared: true
        },
        legend: {
            layout: 'vertical',
            align: 'left',
            x: 120,
            verticalAlign: 'top',
            y: 80,
            floating: true,
            backgroundColor: '#FFFFFF'
        },
        series: [{
            name: 'Both Sexes',
            color: '#455D78',
            type: 'column',
            yAxis: 1,
            data: [19, 68.2, 43.4, 33, 8.3, 38.2, 35.3, 2.8, 6.4, 2.1],
            tooltip: {
                valueSuffix: ' %'
            }
        }, {
            name: 'Women',
            type: 'spline',
            color: '#AA4643',
            yAxis: 2,
            data: [16.7, 63.7, 44.9, 32.2, 7.9, 30.5, 34, 3, 5.1, 1.8],
            marker: {
                enabled: false
            },
            dashStyle: 'shortdot',
            tooltip: {
                valueSuffix: ' %'
            }
        }, {
            name: 'Men',
            color: '#BDCCD4',
            type: 'spline',
            data: [21.3, 72.9, 41.3, 33.6, 8.7, 46, 36.7, 2.6, 7.9, 2.5],
            tooltip: {
                valueSuffix: ' %'
            }
        }]
    });
});

$(function () {
    $('#heartStages').highcharts({
        chart: {
            type: 'column'
        },
        title: {
            text: 'Number of Deaths for Different Types of Heart Diseases in the U.S. for 2008'
        },
        subtitle: {
            text: 'Source: <a href="http://www.nhlbi.nih.gov/resources/docs/2012_ChartBook_508.pdf">'+ 
                'Morbitity & Mortality: 2012 Chart Book on Cardiovascular, Lung and Blood Disease</a>'
        },
        xAxis: {
            categories: [
                'Coronary Heart Disease',
                'Heart Attack',
                'Cardiomyopathy',
                'Stroke',
                'Atrial Fibrillation and Flutter',
                'Heart Failure',
                'Diseases of Pulmonary Circulation',
                'Pulmonary Embolism',
            ],
            labels: {
                rotation: -90,
                align:'right'
            }
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Heart Disease Diagnostic Category (thousands)'
            }
        },
        tooltip: {
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                '<td style="padding:0"><b>{point.y:.1f} </b></td></tr>',
            footerFormat: '</table>',
            shared: true,
            useHTML: true
        },
        plotOptions: {
            column: {
                pointPadding: 0.2,
                borderWidth: 0
            }
        },
        series: [{
            name: 'Heart Disease Related Deaths for 2008',
            data: [405.309, 133.958, 23.932, 134.148, 15.383, 56.830, 12.927, 7.158]

        }]
    });
});

回答by Bob Vork

I got this from another answer, so give thegreyspot some credit in this question.

我从另一个答案中得到了这个,所以在这个问题中给 thegreyspot 一些功劳。

solution: call $(window).resize();after the graph is loaded (or when you fill it with data)

解决方案:$(window).resize();在图形加载后调用(或在填充数据时调用)

回答by Adelos

Just use the chart.reflow()function

只需使用该chart.reflow()功能

回答by Sebastian Bochan

Please take a look at these examples with responsive highcharts:

请查看这些带有响应式高图的示例:

http://jsbin.com/anuqav/1/edit

http://jsbin.com/anuqav/1/edit

http://jsfiddle.net/2gtpA/show/

http://jsfiddle.net/2gtpA/show/

<div id="container" style="width:100%;margin: 0 auto"></div>

回答by Tejpal Sharma

This might help:

这可能有帮助:

$(Highcharts.charts).each(function(i,chart){
    var height = chart.renderTo.clientHeight; 
    var width = chart.renderTo.clientWidth; 
    chart.setSize(width, height); 
  });

回答by ayhtut

for me, it needed to take some delay and trigger the window resize.

对我来说,它需要一些延迟并触发窗口大小调整。

window.setTimeout(function(){ $(window).trigger('resize'); }, 500);

回答by Bruno Ferreira

You can add an event listener so your chart resizes every time it redraws:

您可以添加一个事件侦听器,以便您的图表在每次重绘时调整大小:

mychart = new Highcharts.stockChart('div',   {
    chart: {
        events: {
            redraw: function(e) {
                mychart.reflow();
            }
        }
    },

回答by Thirupathi Govindharaj

In pure javascript multiple charts in single page resize issue on window resize

在纯javascript中,窗口调整大小时单页调整大小问题中的多个图表

 window.onresize = function() {
    //- Remove empty charts if you are using multiple charts in single page 
    //- there may be empty charts
    Highcharts.charts = Highcharts.charts.filter(function(chart){
        return chart !== undefined;
    });

    Highcharts.charts.forEach(function(chart) {
        var height = chart.renderTo.chartHeight;
        //- If you want to preserve the actual height and only want to update 
        //- the width comment the above line.
        //- var height = chart.chartHeight; 
        var width = chart.renderTo.clientWidth;
        //- The third args is an animation set to true. 
        chart.setSize(width, height, true);
    });
};

We need this css code as well

我们也需要这个 css 代码

.highcharts-container {
    width: 100%;
}
.highcharts-container svg {
    width: 100%;
    display: flex;
}

回答by Christopher Charles Gorman

Sort of an old topic now, but I had this issue with IE8. The current version of IE at the time of writing this is IE10, but I needed to make my site compatible with earlier versions. The solution that worked for me was a combination of above and other sites where people spoke about the solution they implemented. I went for a settimeout plus a resize and just executed for IE8, I hope this helps someone else like myself who tried to find a solution for a few hours.

现在有点老话题了,但我在 IE8 上遇到了这个问题。在撰写本文时,IE 的当前版本是 IE10,但我需要使我的站点与早期版本兼容。对我有用的解决方案是上面和其他网站的组合,人们在那里谈论他们实施的解决方案。我去了一个 settimeout 加上一个 resize 并且刚刚为 IE8 执行,我希望这有助于像我这样试图找到几个小时的解决方案的其他人。

You may find just the scriptsection is the only section you require.

您可能会发现只有脚本部分是您需要的唯一部分。

<!--[if IE 8]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <script>
    function timeout() {
        $(window).resize();
    }
    window.setTimeout(function() {
        timeout();
    },2000);
  </script>
  <style>
    .highcharts-container{width:100% !important; height:100% !important;}
  </style>
<![endif]-->

回答by km4Guarana

You can use this code for the example

您可以使用此代码作为示例

var chart;
$(function() {
  var newh = $("#container").height();
    $( window ).resize(function() {
    newh = $("#container").height();
    chart.redraw();
    chart.reflow();
  });
  chart = new Highcharts.Chart();
})

http://jsfiddle.net/Behseini/qheh4w0n/

http://jsfiddle.net/Behseini/qheh4w0n/

回答by Michal Orlík

only this worked for me

只有这对我有用

$(window).resize(function(){ 
    $scope.chartConfig.getChartObj().reflow() 
});