chart.js不同的x轴和工具提示格式

dle*_*ous 2 javascript charts canvas chart.js

我正在尝试使用Charts.js v2库设置条形图.

我遇到的问题是我想要将x轴标签格式化为工具提示标签.

例如,如果我在x轴上有一个类似"将要修剪的超长标签"的标签,下面的代码将显示为"超长标签......".

Chart.scaleService.updateScaleDefaults('category', {
  ticks: {
    callback: function(tick) {
        var characterLimit = 20;
        if ( tick.length >= characterLimit) {
            return tick.slice(0, tick.length).substring(0, characterLimit -1).trim() + '...';;
        } 
        return tick;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

完整的小提琴:https://jsfiddle.net/kvszjr7g/3/

这工作正常.

但是,当您将鼠标悬停在条形图上时显示的工具提示也会被修剪.我想要的是标签的全文显示在工具提示中.

我试过在上面的方法中使用字符串的副本,这就是我添加的原因tick.slice.无论我到目前为止做了什么,总是影响x轴标签和工具提示标签.

在这一点上我很丢失,最好的办法是什么?

tek*_*tiv 15

首先,您最好直接从图表的选项编辑图表属性,而不是像您那样在比例服务中编辑图表属性,这样它就不会影响页面上的每个图表(如果您有多个图表).

要实现您已经完成的任务,请添加您在选项中使用的功能:

options: {
    scales: {
        xAxes: [{
            ticks: {
                callback: function(tick) {
                    var characterLimit = 20;
                    if (tick.length >= characterLimit) {
                        return tick.slice(0, tick.length).substring(0, characterLimit - 1).trim() + '...';
                    }
                    return tick;
                }
            }
        }]
    },
}
Run Code Online (Sandbox Code Playgroud)

它基本上是对xAxe上显示为标签的内容的编辑.


但是,我们仍然遇到同样的问题:标签和工具提示都显示修剪后的字符串.

要修复它,您还需要编辑工具提示的回调:

options: {
    // other options here, `scales` for instance
    // ...
    tooltips: {
        callbacks: {

            // We'll edit the `title` string
            title: function(tooltipItem){
                // `tooltipItem` is an object containing properties such as
                // the dataset and the index of the current item

                // Here, `this` is the char instance

                // The following returns the full string
                return this._data.labels[tooltipItem[0].index];
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


你可以在这个jsFiddle中看到一个完整的例子,结果如下:

在此输入图像描述