设置 Highcharts x 轴标签的宽度

4

我需要设置xAxis标签的最大宽度,这样当标签太长时,剩余的字母(字符)将会换到下一行。

我阅读了Highcharts x轴标签文本换行在设置标签步骤后丢失并发现设置“width”适用于英文单词(由空格分隔)。

但是当没有空格时,例如“VeryLongLongLongWord”或“这是一个很长很长很长的中文”,那就不起作用了。

我还尝试设置wordWrap: break-word,但仍然无济于事。

$(function () {
    $('#container').highcharts({
        chart: {
            type: 'column',
        },
        xAxis: {
            categories: ['This is a long Text', 'VeryLongLongLongWord', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec','这是一个很长很长很长的中文'],
        labels: {
                style:{
                    width:'30px',// not work for text without empty space
                    wordWrap: 'break-word'//no use
                },
                step: 1
            }
        },

        plotOptions: {
            series: {
                pointWidth: 30
            }
        },

        series: [{
            data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
        }]
    });
});

fidder: http://jsfiddle.net/uehbmzgx/

3个回答

11

@Sebastian的解决方案效果很好。

我发现另一个解决方案,使用格式化程序来限制它的宽度:

        labels: {
            useHTML:true,//Set to true
            style:{
                width:'50px',
                whiteSpace:'normal'//set to normal
            },
            step: 1,
            formatter: function () {//use formatter to break word.
                return '<div align="center" style="word-wrap: break-word;word-break: break-all;width:50px">' + this.value + '</div>';
            }
        },

http://jsfiddle.net/uehbmzgx/5/


3

您需要添加带有!important声明的CSS样式。

CSS

.highcharts-axis-labels span{ 
  word-break:break-all!important;
  width:50px!important;
  white-space:normal!important;
}

Highcharts

 xAxis: {
      categories: ['This is a long Text', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec','这是一个很长很长很长的中文'],
      labels: {
          useHTML:true,
          style:{
                width:'50px',
          },
          step: 1
      }
},

Example: http://jsfiddle.net/uehbmzgx/3/


1
最好的方法是动态格式化字符串:

   xAxis : {
          type: 'category', 
          labels: {
            rotation: -90,
            style: {
              color: "#ff0000",
            },
            formatter: function () {//use formatter to check if length of string is greater than 20 and maintain its width.
              if(this.value.length > 20){
                return this.value.substring(0, 17) + '...';
              }
              return this.value;
            }
          },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接