Chart.js實現tooltip一直顯示的問題記錄

效果

這是實現後的效果:

這裏寫圖片描述

版本

在實現這個現實的過程中,Chart.Js的版本也比較重要,這裏使用的版本是2.1.0,請務必確認版本,在更高的版本可能會有更好的方案。

過程

需要在創建的chart前加入:

 Chart.pluginService.register({
        beforeRender: function (chart) {
            if (chart.config.options.showAllTooltips) {
                // create an array of tooltips
                // we can't use the chart tooltip because there is only one tooltip per chart
                chart.pluginTooltips = [];
                chart.config.data.datasets.forEach(function (dataset, i) {
                    chart.getDatasetMeta(i).data.forEach(function (sector, j) {
                        chart.pluginTooltips.push(new Chart.Tooltip({
                            _chart: chart.chart,
                            _chartInstance: chart,
                            _data: chart.data,
                            _options: chart.options,
                            _active: [sector]
                        }, chart));
                    });
                });

                // turn off normal tooltips
                chart.options.tooltips.enabled = false;
            }
        },
        afterDraw: function (chart, easing) {
            if (chart.config.options.showAllTooltips) {
                // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
                if (!chart.allTooltipsOnce) {
                    if (easing !== 1)
                        return;
                    chart.allTooltipsOnce = true;
                }

                // turn on tooltips
                chart.options.tooltips.enabled = true;
                Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
                    tooltip.initialize();
                    tooltip.update();
                    // we don't actually need this since we are not animating tooltips
                    tooltip.pivot();
                    tooltip.transition(easing).draw();
                });
                chart.options.tooltips.enabled = false;
            }
        }
    })

創建表格的記錄:

 this.myChart = new Chart(ctx, {
        type: 'bar',
        data: patientAgeData,
        options: {
            tooltips: {
                callbacks: {
                    label: function (tooltipItem, data) {
                        var i = tooltipItem.index;
                        console.info(data.datasets)
                        var label = data.datasets[0].data[i];
                        return label+"名";
                    }
                }
            },
            showAllTooltips: true
        }
    });

即可完成此任務!查了很多資料,最後才查到此方案,由於對JS瞭解不深。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章