我使用的是 图表.js. 我在下面分享一个例子。当我把鼠标悬停在条形图上时,我得到了总票数的工具提示。
现在我关心的是,是否可以在tooltip中显示多个值。目前,它显示的是 #投票数 5.
我已经展示了一个更喜欢 Amount 40
.
我试过下面的代码,但它不工作。
data: [[12, 19, 3, 5, 2, 3],[10, 20, 30, 40, 50, 60]],
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
//data: [[12, 19, 3, 5, 2, 3],[10, 20, 30, 40, 50, 60]],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
.innerbox {
width: 600px;
height: 300px;
}
<div class="innerbox">
<canvas id="myChart" width="400" height="300"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
你可以使用回调函数 afterLabel
来显示第二个值,像这样。
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
tooltips: {
callbacks: {
afterLabel: function(tooltipItem, data) {
var amount = [10, 20, 30, 40, 50, 60];
return "Amount " + amount[tooltipItem['index']];
}
}
}
}
});
.innerbox {
width: 600px;
height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<div class="innerbox">
<canvas id="myChart" width="400" height="300"></canvas>
</div>