问题
In one html page, I have a select menu (a,b,c,d) and a bar chart (bar a,b,c,d). What I want to do is to highlight the corresponding bar in the bar chart that is selected in the select menu.
回答1:
You can attach the logic to your onchange handler
document.getElementById("mySelect").onchange = highlightBar.bind(document.getElementById("mySelect"));
and if you want to call it programmatically (say, if you have an initial value set)
document.getElementById("mySelect").onchange();
Here's the logic for highlighting the bars. Note that you need to consider the fact that the tooltip functionality also manipulates fill colors and stroke colors.
function highlightBar(s) {
// this clears off any tooltip highlights
myBarChart.update();
myBarChart.activeElements = [];
// reset any coloring because of selection
myBarChart.datasets.forEach(function(dataset) {
dataset.bars.forEach(function (bar) {
if (bar.selected) {
bar.fillColor = bar.selected.fillColor;
bar.strokeColor = bar.selected.strokeColor;
delete bar.selected;
}
})
});
var index = myBarChart.scale.xLabels.indexOf(this.value);
myBarChart.datasets.forEach(function (dataset) {
var selectedBar = dataset.bars[index];
// store the current values
selectedBar.selected = {
fillColor: selectedBar.fillColor,
strokeColor: selectedBar.strokeColor
}
// now set the color
selectedBar.fillColor = "red";
selectedBar.strokeColor = "red";
});
myBarChart.update();
}
If however, you don't have tooltips enabled, it becomes a whole lot simpler and you don't need some of the above logic.
Working Fiddle - http://jsfiddle.net/39owabm0/198/
来源:https://stackoverflow.com/questions/32154202/how-to-highlight-single-bar-in-bar-chart-using-chartjs