【发布时间】:2017-06-09 21:32:51
【问题描述】:
我有一个带有鼠标悬停事件的简单条形图。数据更新前代码仅在函数 changeData 之外工作。但是在数据发生变化后,只能在函数内部工作代码。 如何编写函数来处理所有矩形的鼠标悬停/移出?
使用按钮 OpacityNow 我可以将不透明度更改为所有矩形,无论数据是否已更改。
感谢您的帮助。
var myCanvas1 = d3.select("#chart1")
.append("svg")
.attr("width", svgWidth + margin.left + margin.right)
.attr("height", svgHeight + margin.top + margin.bottom)
.style("background", "aliceblue")
.append("g")
.attr("transform","translate(" + margin.left + "," + margin.top + ")")
.append("g");
//append rectangles to svg container
var Bar = myCanvas1.selectAll("rect")
.data(dataArray1)
.enter()
.append("rect")
.style("fill", "steelblue")
.attr("x", function(d, i) { return x(i); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return (svgHeight - y(+d.balance)); } )
.attr("height", function(d) { return y(+d.balance); })
//.on("mouseover", function() {d3.select(this).attr("opacity", 0.5)})
//.on("mouseout", function() {d3.select(this).attr("opacity", 1)});
//function for button click event
function changeData(myDataArray) {
var Bars = myCanvas1.selectAll("rect");
var NewBars = Bars.data(eval(myDataArray));
//enter new data
NewBars.enter()
.append("rect")
.style("fill", "steelblue")
//.on("mouseover", function() {d3.select(this).attr("opacity", 0.5)})
//.on("mouseout", function() {d3.select(this).attr("opacity", 1)})
.transition()
.duration(duration1)
.attr("x", function(d, i) { return x(i); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return (svgHeight - y(+d.balance)); } )
.attr("height", function(d) { return y(+d.balance); });
//exit data
NewBars.exit()
.remove();
//update data
NewBars.transition()
.duration(duration1)
.style("fill", "steelblue")
.attr("x", function(d, i) { return x(i); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return (svgHeight - y(+d.balance)); } )
.attr("height", function(d) { return y(+d.balance); });
//mouseover and mouseout event functions
d3.select("#chart1").select("svg").selectAll("rect").on("mouseover", function(d) { d3.select(this).attr("opacity", 0.3)});
d3.select("#chart1").select("svg").selectAll("rect").on("mouseout", function(d) { d3.select(this).attr("opacity", 1)});
};
//mouseover and mouseout event functions
d3.select("#chart1").select("svg").selectAll("rect").on("mouseover", function(d) { d3.select(this).style("fill", "red")});
d3.select("#chart1").select("svg").selectAll("rect").on("mouseout", function(d) { d3.select(this).style("fill", "green")});
//function click button to change opacity in all rects
function OpacityNow() {
d3.select("#chart1").select("svg").selectAll("rect").style("opacity", 0.3);
};
//function click button to change color in all rects
function ColorNow() {
d3.select("#chart1").select("svg").selectAll("rect").style("fill", "green");
};
【问题讨论】:
-
您是在问如何编写代码以免重复自己,还是您提供的代码无法以某种方式工作?
标签: javascript d3.js mouseover