How to toggle legend layout in highchart

2019-08-29 05:40发布

问题:

I am interested to change legend layout on click event as below

1st click horizontal - bottom

2nd click horizontal top

3rd click virtical left

4th click virtical right

Here is Link to FIDDLE

I don't know how this can be done, this is what I have tried so far.

HTML

      <script src="http://code.highcharts.com/highcharts.js"></script>
      <div id="container" style="height: 400px"></div>
      <input id='legend' type='button' value='toggle legend'>

JAVASCRIPT

       $(function () {
var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        zoomType: 'xy',
        marginLeft: 50,
        marginBottom: 90
    },

    yAxis: {
        reversed: true,
        //min: 0,
        //max: 50
    },
    plotOptions: {
        series: {
            stacking: 'normal'
        }
    },
    xAxis: {
        opposite: true  
    },
    series: [{
        name: '01-Jan-2014',
        data: [
            [28, 10],
            [30, 0]
        ]
    }]
});


var last = 0;
$('#legend').click(function(){

     var arr  = ['vertical','horizontal'];
     if(last>arr.length){last=0;}
    setTimeout(function() { alert(arr[last++]);},10);  
     chart.series[0].update({ legend: { layout: arr[last] }});

    });

    });

回答1:

Here's a way to do it here. I hate resorting to setting the internal dirty flags but it seems to work well:

var somePositions = [['center','bottom'],
                     ['center','top'],
                     ['left','middle'],
                     ['right','middle']];

 $('#btn').click(function(){
      posIdx++;
      if (posIdx == 4) posIdx = 0;                
      chart.legend.options.align = somePositions[posIdx][0];
      chart.legend.options.verticalAlign = somePositions[posIdx][1];
      chart.isDirtyLegend = true;
      chart.isDirtyBox = true;
      chart.redraw();
 });


回答2:

You need to use tranlsate() function which allows to move SVG elements like legend.

var legend = chart.legend.group;

        $('#btn').click(function(){
            legend.translate(0,0)
        });

http://jsfiddle.net/F3cSa/1/