要在Chart.js 2.7.3中显示所有的tooltip,可以使用以下代码:

Chart.defaults.global.tooltips.enabled = false;

Chart.defaults.global.tooltips.custom = function(tooltip) {
    // Tooltip Element
    var tooltipEl = document.getElementById('chartjs-tooltip');

    // Create element on first render
    if (!tooltipEl) {
        tooltipEl = document.createElement('div');
        tooltipEl.id = 'chartjs-tooltip';
        tooltipEl.innerHTML = '<table></table>';
        document.body.appendChild(tooltipEl);
    }

    // Hide if no tooltip
    if (tooltip.opacity === 0) {
        tooltipEl.style.opacity = 0;
        return;
    }

    // Set caret Position
    tooltipEl.classList.remove('above', 'below', 'no-transform');
    if (tooltip.yAlign) {
        tooltipEl.classList.add(tooltip.yAlign);
    } else {
        tooltipEl.classList.add('no-transform');
    }

    // Set Text
    if (tooltip.body) {
        var innerHtml = '<thead>';

        tooltip.body.forEach(function(bodyItem) {
            innerHtml += '<tr><th>' + bodyItem.lines + '</th></tr>';
        });
        innerHtml += '</thead><tbody>';

        tooltip.title.forEach(function(titleItem) {
            innerHtml += '<tr><td>' + titleItem + '</td></tr>';
        });
        innerHtml += '</tbody>';

        var tableRoot = tooltipEl.querySelector('table');
        tableRoot.innerHTML = innerHtml;
    }

    // `this` will be the overall tooltip
    var position = this._chart.canvas.getBoundingClientRect();

    // Display, position, and set styles for font
    tooltipEl.style.opacity = 1;
    tooltipEl.style.position = 'absolute';
    tooltipEl.style.left = position.left + window.pageXOffset + tooltip.caretX + 'px';
    tooltipEl.style.top = position.top + window.pageYOffset + tooltip.caretY + 'px';
    tooltipEl.style.fontFamily = tooltip._fontFamily;
    tooltipEl.style.fontSize = tooltip.fontSize;
    tooltipEl.style.fontStyle = tooltip._fontStyle;
    tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
    tooltipEl.style.pointerEvents = 'none';
};

这将禁用默认的tooltip,并在鼠标悬停时创建一个自定义的tooltip元素。要使用这个代码,将其放在Chart.js图表的初始化代码中,例如:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        // ...
    },
    options: {
        // ...
    }
});

Chart.defaults.global.tooltips.enabled = false;

Chart.defaults.global.tooltips.custom = function(tooltip) {
    // ...
};

请注意,在这种情况下,您需要在HTML页面中创建一个具有id“chartjs-tooltip”的div元素,以便tooltip能够显示在正确的位置。例如:

<div id="chartjs-tooltip"></div>

希望这可以帮助你显示所有的tooltip!

chartjs273显示所有tooltip

原文地址: https://www.cveoy.top/t/topic/No2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录