我有一个饼图,当您单击图表的一部分时,需要调用一个函数;如果单击图例中的标签,则需要调用另一个不同的函数。我希望通过以下方式实现此行为:
options: {
responsive: true,
legend: {
position: 'right',
onClick: function (event, elem) {
graph_legend_click(elem.text);
},
},
onClick: function (event) {
graph_click( event);
}
}
但实际上,只有第二个 onclick(调用 graph_click(event);
)才会真正执行。图例 onClick
不起作用。
我该怎么做才能防止第二个 onClick 覆盖第一个?
最佳答案
只能通过坐标来区分点击事件......条件是:
event.clientY >= chart.boxes[0].height
,当legend
已开启top
.event.clientX <= chart.boxes[0].left
,当legend
是right
.
也可以使用类似的条件,当 legend
是left
或访问bottom
.
var chart;
var config = {
type: 'pie',
data: {
datasets: [{
data: [
Math.round(Math.random() * 100),
Math.round(Math.random() * 100),
Math.round(Math.random() * 100),
Math.round(Math.random() * 100),
Math.round(Math.random() * 100)
],
backgroundColor: [
"rgb(255, 99, 132)",
"rgb(255, 159, 64)",
"rgb(255, 205, 86)",
"rgb(75, 192, 192)",
"rgb(54, 162, 235)"
],
label: 'Dataset 1'
}],
labels: [
'Red',
'Orange',
'Yellow',
'Green',
'Blue'
]
},
options: {
responsive: true,
onClick: function (event) {
/* checking where the click actually happens */
var box = chart.boxes[0];
if((box.position === "top" && event.clientY >= box.height) || (box.position === "right" && event.clientX <= box.left)) {
console.log("chart click @ x: " + event.clientX + ", y:" + event.clientY);
}
},
legend: {
position: 'top',
onClick: function (event, elem) {
console.log("legend click @ x: " + event.clientX + ", y:" + event.clientY);
}
}
}
};
$(function() {
chart = new Chart($('#chart-area')[0].getContext('2d'), config);
});
html, body {height: 100%; width: 100%; margin: 0;}
canvas#chart-area {height: 100px; width: 100px;}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<div id="canvas-holder"><canvas id="chart-area"></canvas></div>
关于javascript - Chart.js:饼图图例 "onclick"会被 "options.onclick"覆盖(如果两者都存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52381043/