问题:
如下图所示,需要在tooltip中显示较长的字符串时,gantt是不会自动换行的,导致tooltip显示很长,不美观。
- 如果想让较长的文字换行,可以把文字截取分为几个部分,每个部分之间使用
<br>
来换行。
Highcharts.ganttChart('container', {
...
tooltip: {
useHTML: true,
pointFormatter: function () {
var point = this,
format = '%e. %b',
options = point.options,
completed = options.completed,
amount = isObject(completed) ? completed.amount : completed,
status = ((amount || 0) * 100) + '%',
lines;
var len = 15; // 每段的长度为10个字符
var strReg = new RegExp(`.{1,${len}}`, 'g');
let content = '';
if(options.content){
// 切分字符串
const str = options.content.match(strReg);
content = str.join('<br/>');
}
lines = [{
value: point.name,
style: 'font-weight: bold;'
}, {
title: 'Start',
value: dateFormat(format, point.start)
}, {
visible: !options.milestone,
title: 'End',
value: dateFormat(format, point.end)
}, {
title: 'Completed',
value: status
}, {
title: 'Content',
value: content,
}, {
title: 'Owner',
value: options.owner || 'unassigned'
}];
return lines.reduce(function (str, line) {
var s = '',
style = (
defined(line.style) ? line.style : 'font-size: 0.8em;'
);
if (line.visible !== false) {
s = (
'<span style="' + style + '">' +
(defined(line.title) ? line.title + ': ' : '') +
(defined(line.value) ? line.value : '') +
'</span><br/>'
);
}
return str + s;
}, '');
}
}
...
}
- 还可以把tooltip中的内容改为HTML渲染,而不是SVG,在SVG中渲染不能使用复杂的样式,比如margin和padding等,但改为HTML渲染就没问题了。
Highcharts.ganttChart('container', {
...
tooltip: {
useHTML: true,
pointFormatter: function () {
var point = this,
format = '%e. %b',
options = point.options,
completed = options.completed,
amount = isObject(completed) ? completed.amount : completed,
status = ((amount || 0) * 100) + '%',
lines;
lines = [{
value: point.name,
style: 'font-weight: bold;'
}, {
title: 'Start',
value: dateFormat(format, point.start)
}, {
visible: !options.milestone,
title: 'End',
value: dateFormat(format, point.end)
}, {
title: 'Completed',
value: status
}, {
title: 'Content',
value: options.content,
}, {
title: 'Owner',
value: options.owner || 'unassigned'
}];
return lines.reduce(function (str, line) {
var s = '',
style = (
defined(line.style) ? line.style : 'font-size: 0.8em;'
);
if (line.visible !== false) {
s = (
'<span style="white-space: pre-wrap;' + style + '">' +
(defined(line.title) ? line.title + ': ' : '') +
(defined(line.value) ? line.value : '') +
'</span><br/>'
);
}
return `<div style="width:200px;">${str + s}</div>`;
}, '');
}
},
...
}
- tooltip开启 useHTML: true 使用HTML渲染
- 在返回tooltip内容结构中,一个
<span>
代表一行,行行之间使用<br>
换行,但当一行内容过长时需要自动换行,所以需要添加样式white-space: pre-wrap;
- 在设置行样式后,还需要给所有的
<span>
套个父级元素<div>
,并设置宽度,来触发自动换行。