在正常情况下,Highcharts的饼图显示效果良好,如下图所示
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares January, 2015 to May, 2015'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: [{
name: "Microsoft Internet Explorer",
y: 56.33
}, {
name: "Chrome",
y: 24.03,
sliced: true,
selected: true
}, {
name: "Firefox",
y: 10.38
}, {
name: "Safari",
y: 4.77
}, {
name: "Opera",
y: 0.91
}, {
name: "Proprietary or Undetectable",
y: 0.2
}]
}]
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
</body>
</html>
但如果data中的name,也就是后台传入的数据字段很长的时候,就会出现一个问题,如下图所示
这是神马怪异的现象?
对于这种问题,解决的方法就是给dataLabels加个样式,让宽度有个限制,使得文字能够自动换行,局部代码如下
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
width: '100px', // 重点在此
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
效果如下
但是,对于英文,这种方法可行,但是遇到中文,就行不通了
因为中文词与词之间可没有空格。这时只能让他强制换行,代码如下(由于要重写dataLabel的展现,必须用到 formatter)
dataLabels: {
enabled: true,
useHTML: true, // 一定要加上
formatter : function() {
return "<p style='width: 100px; display:inline-block; white-space:pre-wrap;'><b>"+this.point.name+"</b>: "+this.percentage.toFixed(2)+" %</p>"; // 重点在white-space:pre-wrap
}
}
效果如下
总结一下,最主要的是white-space:pre-wrap;的使用,其他的也没什么。
给予了灵感的链接:
1. Highcharts API
http://www.hcharts.cn/api/index.php#plotOptions.pie.dataLabels
2. Highcharts Pie Chart.How to set labels in two lines
http://stackoverflow.com/questions/18329478/highcharts-pie-chart-how-to-set-labels-in-two-lines
3. CSS white-space 属性
http://www.w3school.com.cn/cssref/pr_text_white-space.asp
所用示例为Highcharts官方examples下的pie-basic。