设置Highcharts x轴标签的宽度

时间:2015-12-02 07:30:38

标签: javascript html css highcharts

我需要为xAxis Label设置最大宽度,以便当它太长而其余的字母(字符)将转到下一行。

我看了Highcharts x axis label text wrapping lost on setting label step并且发现设置“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 个答案:

答案 0 :(得分:6)

@ Sebastian的解决方案运行良好。

我找到了另一个解决方案,使用formatter来限制它的宽度:

        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/

答案 1 :(得分: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
      }
},

示例:http://jsfiddle.net/uehbmzgx/3/

答案 2 :(得分:0)

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

   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;
            }
          },