我有这段代码,它使用 c3.js 制作图表:https://jsfiddle.net/1bxe2scd/
<!DOCTYPE html>
<html>
<head>
<title>Dsnap - Charts</title>
<!-- Load c3.css -->
<link href="c3/c3.css" rel="stylesheet" type="text/css">
<!-- Load d3.js and c3.js -->
<script src="d3/d3.min.js" charset="utf-8"></script>
<script src="c3/c3.min.js"></script>
</head>
<body>
<div id="chart" style="width:480px;height:400px"></div>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var chart = c3.generate({
bar: {
width: 15
},
padding: {
left: 60
},
data: {
x: 'Date',
columns:
[
['Date', '2011-02','2013-01','2013-02','2013-03','2013-04','2013-05','2013-06','2013-07','2013-08','2013-09','2013-10','2013-11','2013-12','2014-01','2014-02'],
['value', 777,53,165,269,344,376,410,421,405,376,359,392,433,455,978]
],
type: 'bar',
onclick: function(e) { console.log(e.x);}
},
axis: {
rotated: true,
x: {
type: 'category'
}
},
tooltip: {
grouped: false
},
legend: {
show: false
}
});
</script>
</body>
</html>
我希望用户点击的栏获得焦点,而栏的其余部分应该变淡,我怎样才能实现这一点?
如何获取点击栏的 Y 值(例如:2011-02 等)?
最佳答案
您可以执行此操作来突出显示该栏:
onclick: function(e) {
//make all the bar opacity 0.1
d3.selectAll(".c3-shape").style("opacity",0.1);
var k = ".c3-shape-"+ e.index;
//make the clicked bar opacity 1
d3.selectAll(k).style("opacity",1)
}
工作代码here
单击图表中的外侧时,如果您希望恢复所有条形,请将单击监听器附加到图表,然后单击使所有条形的不透明度为 1:
d3.selectAll("#chart").on("click", function(d) {
//reset all the bars
d3.selectAll(".c3-shape").style("opacity", 1);
})
工作代码here
编辑
现在,由于您有两个图表,因此还指定了 id,使其特定于图表,请注意选择器中的 id:(#chart/#chart1):
d3.selectAll("#chart1").on("click", function(d) {
//reset all the bars for chart1
d3.selectAll("#chart1 .c3-shape").style("opacity", 1);
})
d3.selectAll("#chart").on("click", function(d) {
//reset all the bars for chart
d3.selectAll("#chart .c3-shape").style("opacity", 1);
})
单击图表 1 栏将如下所示:
onclick: function(e) {
//make all the bar opacity 0.1 for chart1
d3.selectAll("#chart1 .c3-shape").style("opacity", 0.1);
var k = "#chart1 .c3-shape-" + e.index;
//make the clicked bar opacity 1
d3.selectAll(k).style("opacity", 1)
event.stopPropagation()
}
工作代码here
希望这有帮助!
关于javascript - 如何在C3.js条形图中聚焦点击的条形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35008483/