问题
I faced a similar problem to what was described HERE:
The solution that worked for me, was to implement the following code:
$(function () {
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
window.dispatchEvent(new Event('resize'));
});
});
I have a feeling, however, that ALL of the charts are being re-rendered, regardless of whether they are on the active tab (visible) or in the non-selected tabs (hidden). If for example I have 20 tab pages, it takes far longer to re-render than it does for 2 tab pages.
Does anyone know how to ensure ONLY the active chart gets resized / redrawn? Ie how can the resize / redraw event be suppressed if the chart is not visible?
回答1:
What I did was to store all my charts in an array when they are first created. I know that 'chart1' is a child of 'tab1', 'chart2' is a child of 'tab2' etc... (by design), so I can determine the index in the array using some regex.
Once the index is known, we can refresh the chart object directly, accessed from the array by zero-based index.
//Resize Event needs to be triggered when tab changes.
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
var plotID, ev;
try{
plotID = $(e.target).attr("href").replace(/[#A-Za-z$-]/g,"")
d3.select("#chart"+ plotID +" svg").call(charts[(plotID-1)])
}catch(err){ //Fallback
ev = document.createEvent('Event');
ev.initEvent('resize', true, true);
window.dispatchEvent(ev);
}
});
Net result, redraw times much much faster when compared to triggering resize event.
来源:https://stackoverflow.com/questions/29191348/nvd3-chart-suppress-rendering-for-hidden-charts