作者:半E冷半柔半妖娆 | 来源:互联网 | 2023-01-29 13:53
我有以下使用chart.js的折线图示例.我想表明:
悬停时图例和标签的指针光标
在线悬停上显示所有标签数据
var line_chart = new Chart(document.getElementById("line-chart"), {
type: 'line',
data: {
labels: ['May', 'June', 'July'],
datasets: [{
data: [15, 25, 15],
label: "My Dataset1",
borderColor: "#00F",
fill: false
}, {
data: [35, 15, 25],
label: "My Dataset2",
borderColor: "#F00",
fill: false
}
]
},
options: {
tooltips: {
mode: 'label',
},
hover: {
mode: 'label'
},
}
});
1> ɢʀᴜɴᴛ..:
更好的方法
不需要jQuery来选择canvas element(line-chart
).
1▸解决方案:
在图表选项中添加以下内容:
legend: {
onHover: function(e) {
e.target.style.cursor = 'pointer';
}
},
hover: {
onHover: function(e) {
var point = this.getElementAtEvent(e);
if (point.length) e.target.style.cursor = 'pointer';
else e.target.style.cursor = 'default';
}
}
2▸解决方案:
集提示的 mode
到dataset
:
tooltips: {
mode: 'dataset'
}
ᴡᴏʀᴋɪɴɢᴡᴏʀᴋɪɴɢxᴀᴍᴘʟᴇ⧩
var line_chart = new Chart(document.getElementById("line-chart"), {
type: 'line',
data: {
labels: ['May', 'June', 'July'],
datasets: [{
data: [15, 25, 15],
label: "My Dataset1",
borderColor: "#00F",
fill: false
}, {
data: [35, 15, 25],
label: "My Dataset2",
borderColor: "#F00",
fill: false
}]
},
options: {
tooltips: {
mode: 'dataset',
},
legend: {
onHover: function(e) {
e.target.style.cursor = 'pointer';
}
},
hover: {
onHover: function(e) {
var point = this.getElementAtEvent(e);
if (point.length) e.target.style.cursor = 'pointer';
else e.target.style.cursor = 'default';
}
}
}
});
2> Luca Fagioli..:
使用Chart.js 2.x,我发现这种方法更加优雅。只需在选项中添加:
events: ['mousemove'], // this is needed, otherwise onHover is not fired
onHover: (event, chartElement) => {
event.target.style.cursor = chartElement[0] ? 'pointer' : 'default';
}
希望能帮助到你。