Morris.js chart not working inside of a bootstrap tab

前端 未结 2 1249
[愿得一人]
[愿得一人] 2021-02-14 02:23

I have a situation where I am trying to use MorrisJS charts inside two different bootstrap tabs. The chart loads fine in the first (default) tab but when I click into the secon

2条回答
  •  野性不改
    2021-02-14 02:31

    Set the Morris.Bar property resize to true:

    resize: true
    

    Assign your Morris.Bar to a variable:

    var homeBar = Morris.Bar({...});
    var profileBar = Morris.Bar({...});
    

    Add an event triggered on tab change that redraws the bar chart and triggers a resize:

    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
      var target = $(e.target).attr("href") // activated tab
    
      switch (target) {
        case "#home":
          homeBar.redraw();
          $(window).trigger('resize');
          break;
        case "#profile":
          profileBar.redraw();
          $(window).trigger('resize');
          break;
      }
    });
    

    See full working snippet below:

    var homeBar = Morris.Bar({
      element: 'chart1',
      data: [
        { y: '2006', a: 100, b: 90 },
        { y: '2007', a: 75, b: 65 },
        { y: '2008', a: 50, b: 40 },
        { y: '2009', a: 75, b: 65 },
        { y: '2010', a: 50, b: 40 },
        { y: '2011', a: 75, b: 65 },
        { y: '2012', a: 100, b: 90 }
      ],
      xkey: 'y',
      ykeys: ['a', 'b'],
      labels: ['Series A', 'Series B'],
      hideHover: 'always',
      resize: true
    });
    
    var profileBar = Morris.Bar({
      element: 'chart2',
      data: [
        { y: '2006', a: 100, b: 90 },
        { y: '2007', a: 75, b: 65 },
        { y: '2008', a: 50, b: 40 },
        { y: '2009', a: 75, b: 65 },
        { y: '2010', a: 50, b: 40 },
        { y: '2011', a: 75, b: 65 },
        { y: '2012', a: 100, b: 90 }
      ],
      xkey: 'y',
      ykeys: ['a', 'b'],
      labels: ['Series A', 'Series B'],
      hideHover: 'always',
      resize: true
    });
    
    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
      var target = $(e.target).attr("href") // activated tab
    
      switch (target) {
        case "#home":
          homeBar.redraw();
          $(window).trigger('resize');
          break;
        case "#profile":
          profileBar.redraw();
          $(window).trigger('resize');
          break;
      }
    });
    
    
    
    
    
    
    
    
    
    
    
    

提交回复
热议问题