Not*_*ras 2 javascript chart.js chartjs-2.6.0
我有一个饼图,当您单击图表的一段时需要调用一个函数,如果单击图例中的标签,则需要调用另一个函数。我希望通过以下方式实现这种行为:
options: {
responsive: true,
legend: {
position: 'right',
onClick: function (event, elem) {
graph_legend_click(elem.text);
},
},
onClick: function (event) {
graph_click( event);
}
}
Run Code Online (Sandbox Code Playgroud)
然而在实践中,只有第二个 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);
});Run Code Online (Sandbox Code Playgroud)
html, body {height: 100%; width: 100%; margin: 0;}
canvas#chart-area {height: 100px; width: 100px;}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5238 次 |
| 最近记录: |