2016-02-28 187 views
1

我一直在試圖理解爲什麼Charts.js如果它在Bootstrap Accordion之內,不會繪製圖表。Charts.js&Bootstrap手風琴

經過多次嘗試,我終於明白了爲什麼它不繪製圖表!這是因爲面板基本上是隱藏的畫布,所以Charts.js不會繪製它。

任何人都可以幫我想出一個解決方案嗎?

我也試圖只在引導事件shown.bs.collapse處於活動狀態時才繪製圖表,不起作用。

這裏有一個jsfiddle我創建來說明這個問題:如果你想重現該問題只需在行<div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">

回答

2

我把它用下面的代碼工作添加in到類

<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> 
    <div class="panel panel-default"> 
    <div class="panel-heading" role="tab" id="headingOne"> 
     <h4 class="panel-title"> 
     <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> 
      Collapsible Group Item #1 
     </a> 
     </h4> 
    </div> 
    <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne"> 
     <div class="panel-body"> 
     <canvas id="q_chart" width="400" height="400"></canvas> 
     </div> 
    </div> 
    </div> 
</div> 

和JavaScript

var ctx = document.getElementById("q_chart").getContext("2d"); 
var data = { 
    labels: ["January", "February", "March", "April", "May", "June", "July"], 
    datasets: [{ 
     label: "My First dataset", 
     fillColor: "rgba(220,220,220,0.2)", 
     strokeColor: "rgba(220,220,220,1)", 
     pointColor: "rgba(220,220,220,1)", 
     pointStrokeColor: "#fff", 
     pointHighlightFill: "#fff", 
     pointHighlightStroke: "rgba(220,220,220,1)", 
     data: [65, 59, 80, 81, 56, 55, 40] 
    }, { 
     label: "My Second dataset", 
     fillColor: "rgba(151,187,205,0.2)", 
     strokeColor: "rgba(151,187,205,1)", 
     pointColor: "rgba(151,187,205,1)", 
     pointStrokeColor: "#fff", 
     pointHighlightFill: "#fff", 
     pointHighlightStroke: "rgba(151,187,205,1)", 
     data: [28, 48, 40, 19, 86, 27, 90] 
    }] 
}; 
var MyNewChart=null; 
$('#collapseOne').on('shown.bs.collapse', function() { 
    setTimeout(function() { 
     if(MyNewChart == null) 
      MyNewChart = new Chart(ctx).Bar(data); 
    },200); 
}); 
+0

對,它的工作,現在...你介意解釋爲什麼你的代碼工作? :) – odedta

+1

@odedta正如你所說,chartjs不起作用,因爲面板基本上隱藏了畫布,所以我們需要在面板顯示時運行chartjs,但當面板被盜時會觸發事件'shown.bs.collapse'hide(僅在面板顯示完成之前幾毫秒),所以我只是創建一個延遲,以確保面板完全顯示 – Shayan

+0

我明白了,非常感謝! – odedta

0

對於任何後來的人來說,我有同樣的問題,但不願意依賴接受答案中提供的計時器延遲。下面是使用引導3.3.7與顯示事件什麼工作對我來說:顯示

.bs.collapse

$('#accordion').on('shown.bs.collapse', function (e) { 

      switch (e.target.id) 
      { 
       case "panel1": ShowChart1(); break; 
       case "panel2": ShowChart2(); break; 
       case "panel3": ShowChart3(); break; 
       case "panel4": ShowChart4(); break; 
       default: ShowDefault(); 
      } 

     }) 

希望這有助於

順便說一句 - 這是上面的代碼工作:greatdata.com/stats/newyork_ny