问题
I have a column chart from amcharts. I need to highlight a single bar on click on bar. Current scenario is when I click multiple bar, all bars highlighted.
enter image description here
var highState = series.columns.template.states.create("highlight");
highState.properties.fill = am4core.color("#8c8c8c");
var highState = series.columns.template.states.create("default");
highState.properties.fill = am4core.color("#333333");
var activeState = series.columns.template.states.create("active");
activeState.properties.fill = am4core.color("#E94F37");
series.columns.template.events.on("hit", function(ev) {
for (var j = 0; j < !ev.target.isActive.length; ++j) {
if (ev.target.isActive) {
series.columns.template.setState("default");
ev.target.setState("default");
ev.target.isActive = !ev.target.isActive;
}
else {
State = undefined;
!series.columns.template.setState("active");
ev.target.isActive = !ev.target.isActive;
series.columns.template.setState("highlight"); ev.target.isActive;
State = ev.target.isActive;
}
}
});
回答1:
To highlight a single column on click, first make the columns toggleable:
series.columns.template.togglable = true;
Now, when you click a column, it will toggle between its active and default states along, so you just need to create the active state and define its properties. You're already doing that with these 2 lines of code:
var activeState = series.columns.template.states.create("active");
activeState.properties.fill = am4core.color("#E94F37");
And that's it! No need for hit events and the like.
If you want it so that only one column is ever highlighted at a time, then we do need a hit event, we'll just reset every column except the one that was clicked (whether they were active or not is irrelevant). The series.columns
is a list template, so it has an each
method that allows us to iterate over all the actual columns (a lot like Array.forEach
):
series.columns.template.events.on("hit", function(event) {
series.columns.each(function(column) {
if (column !== event.target) {
column.setState("default");
column.isActive = false;
}
})
});
Here's a demo:
https://codepen.io/team/amcharts/pen/abd6da81e3bd7004f70eb6069a135219
来源:https://stackoverflow.com/questions/54234525/how-to-highlight-a-single-bar-on-click-in-amcharts-v4