gpt4 book ai didi

javascript - 如何禁用图表js图例点击

转载 作者:行者123 更新时间:2023-12-03 21:41:11 25 4
gpt4 key购买 nike

我想禁用 Chart.js 蜘蛛图图例单击,因为当我单击图例时,数据系列会隐藏关联的值集,如下图所示。

enter image description here

enter image description here

我的要求是我不想禁用数据集。我已经尝试过 PreventDefault();在图表上单击但它不起作用。

我的代码示例附在下面。请检查..

<!doctype html>
<html>

<head>
<title>Radar Chart</title>
<script src="../dist/Chart.bundle.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>
<div style="width:75%">
<canvas id="canvas"></canvas>
</div>
<script>
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var randomColorFactor = function() {
return Math.round(Math.random() * 255);
};
var randomColor = function(opacity) {
return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';
};

var config = {
type: 'radar',
data: {
labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
datasets: [{
label: "My First dataset",
backgroundColor: "rgba(0,0,0,0.5)",
pointBackgroundColor: "rgba(220,220,220,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}, {
label: "My Second dataset",
backgroundColor: "rgba(0,120,0,0.5)",
pointBackgroundColor: "rgba(151,187,205,1)",
hoverPointBackgroundColor: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
},]
},
options: {
legend: {
position: 'top',
onClick: (e) => e.stopPropagation()
},
title: {
display: true,
text: ''
},
scale: {
reverse: false,
gridLines: {
color: ['black']
},
ticks: {
beginAtZero: true
}
}
}
};

window.onload = function() {
window.myRadar = new Chart(document.getElementById("canvas"), config);
};





</script>
</body>

</html>

最佳答案

根据文档,有一个用于公开事件对象的图例的 onClick 处理程序。如果您stopPropagation,它会停止隐藏数据系列:

        let chart = new Chart(elem.find('canvas')[0], {
type: 'line',
data: {
labels: [],
datasets: []
},
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
onClick: (e) => e.stopPropagation()
}
}
});
<小时/>

以上是 ES6,如果您不使用受支持的浏览器,则以下是较旧的 ES5 等效浏览器。

legend: {
onClick: function (e) {
e.stopPropagation();
}
}

Chartjs 必须在 legend.onClick 之后注册自己的点击事件,这就是它停止执行的原因。

docs

关于javascript - 如何禁用图表js图例点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38583894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com