我在代码中使用 Highcharts。目前,当用户单击图例项(例如“ABC”)时,标记为“ABC”的相应饼图将变为灰色。再次单击时,灰色将被删除,饼图将恢复到其原始颜色。现在,我希望通过在饼图变灰时向“ABC”图例项添加删除线效果来增强此功能,并在饼图返回到原始颜色时删除删除线。
Highcharts.chart('container', {
series: [{
type: 'pie',
data: [1, 2, 3, 4],
showInLegend: true,
point: {
events: {
legendItemClick: function() {
var originalColor = this.options.originalColor; // Retrieve original color from options
var newColor = (this.color === 'gray') ? originalColor : 'gray'; // Toggle between gray and original color
// Toggle visibility of data labels
var showDataLabels = (newColor !== 'gray');
this.update({
color: newColor,
dataLabels: {
enabled: showDataLabels
}
});
return false;
}
}
},
events: {
afterInit: function() {
// Store original color for each point
this.points.forEach(function(point) {
point.options.originalColor = point.color;
});
}
}
}],
accessibility: {
enabled: false,
},
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
由于 Highcharts 将其图表生成为 SVG,因此您不能使用普通的 CSS 样式。
黑客解决方法是使用 JS 事件并在 Highcharts 应用样式后覆盖样式。
如果这有帮助,请告诉我。
Highcharts.chart('container', {
series: [{
type: 'pie',
data: [1, 2, 3, 4],
showInLegend: true,
point: {
events: {
legendItemClick: function() {
var originalColor = this.options.originalColor; // Retrieve original color from options
var newColor = (this.color === 'gray') ? originalColor : 'gray'; // Toggle between gray and original color
// Toggle visibility of data labels
var showDataLabels = (newColor !== 'gray');
this.update({
color: newColor,
dataLabels: {
enabled: showDataLabels
}
});
return false;
}
}
},
events: {
afterInit: function() {
// Store original color for each point
this.points.forEach(function(point) {
point.options.originalColor = point.color;
});
}
}
}],
accessibility: {
enabled: false,
},
});
const items = document.querySelector('svg').querySelectorAll('.highcharts-legend-item text');
items.forEach((item, index) => {
item.addEventListener('mouseover', (ev) => {
// HACK: this timeout is to override the style after highcharts applies its own style
setTimeout(() => {
ev.target.style.textDecoration = 'line-through';
}, 100);
});
item.addEventListener('mouseout', (ev) => {
ev.target.style.textDecoration = '';
});
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>