有人能告诉我我的代码有什么问题吗?我已经使用Chart.js成功生成了一个圆环图,以及一个图例,但是当我将鼠标悬停在图例中的每个项目上时,我希望图表的相应部分用工具提示突出显示,就像它是如何做的一样在this页面上
我试过复制并修改那个确切页面上使用的代码,但我无法让它工作。建议和帮助赞赏!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Chart.js demo</title>
<script src='Chart.js'></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="race" width="250" height="250" style="width: 250px; height: 250px;"></canvas>
<ul class="doughnut-legend">
<li><span style="background-color:#40af49"></span>African American</li>
<li><span style="background-color:#ac558a"></span>Other</li>
<li><span style="background-color:#f05541"></span>Multi-Racial, Not Hispanic</li>
<li><span style="background-color:#3ac2d0"></span>Hispanic/Latino</li>
<li><span style="background-color:#faaf3c"></span>Asian</li>
<li><span style="background-color:#4287b0"></span>White/Caucasian</li>
</ul>
<script>
var pieData = [
{
value: 24.8,
color: "#40af49",
label: "African American"
},
{
value : 2.9,
color : "#ac558a",
label: "Other"
},
{
value : 5.7,
color : "#f05541",
label: "Multi-Racial, Not Hispanic"
},
{
value : 19.1,
color : "#3ac2d0",
label: "Hispanic/Latino"
},
{
value : 6.5,
color : "#faaf3c",
label: "Asian"
},
{
value : 41,
color : "#4287b0",
label: "White/Caucasian"
}
];
var race = new Chart(document.getElementById("race").getContext("2d")).Doughnut(pieData, { tooltipTemplate : "<%if (label){%><%=label%>: <%}%><%= value %>%", animateRotate: true });
var legendHolder = document.createElement('div');
legendHolder.innerHTML = race.generateLegend();
// Include a html legend template after the module doughnut itself
helpers.each(legendHolder.firstChild.childNodes, function(legendNode, index){
helpers.addEvent(legendNode, 'mouseover', function(){
var activeSegment = race.segments[index];
activeSegment.save();
race.showTooltip([activeSegment]);
activeSegment.restore();
});
});
helpers.addEvent(legendHolder.firstChild, 'mouseout', function(){
race.draw();
});
canvas.parentNode.parentNode.appendChild(legendHolder.firstChild);
</script>
</body>
答案 0 :(得分:7)
如果您尝试使用“帮助者”和“画布”,则无法使用它们。
Helpers是指Chartjs助手,可以通过创建
轻松添加var helpers = Chart.helpers
Canvas是指种族变量画布,所以只需添加
race.chart.canvas.parentNode.parentNode.appendChild(legendHolder.firstChild);
here是工作的小提琴