问题
everyone. I've got one question about how to return the data.value with the "mouse" event. The following code can get the current X-Position(show on the ), while I've no idea how to return the obj.value.
I've checked the method used at drought-crops, but still stuck on it.
Can anyone give me some ideas about it? I guess some of you have met such kind of scenario.
Inspired from Zoomable Area and Zoomable Map Tiles created by mbostock. (Add the following code into Zoomable Area to debug)
<style>
.info {
position: absolute;
top: 100px;
left: 50px;
}
</style>
<script>
svg.append("rect")
.attr("class", "pane")
.attr("width", width)
.attr("height", height)
.call(zoom)
.on("mousemove", mousemoved);
var info = svg.append("text").attr("class","info");
function mousemoved() {
//work with the x position returned, but no idea how to return the d.value
info.text(d3.mouse(this));
}
</script>
回答1:
http://bl.ocks.org/mbostock/3902569
function mousemove() {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - d0.date > d1.date - x0 ? d1 : d0;
...
}
This is code provided by an example from Mike.
First you get the x-value of the scale you are using on the position of the mouse. Then a bisector is used to get the two closest values of your underlying data. You then select the appropriate one and can display it.
If you want you can interpolate either manually between your two data points or use the getPointAtLength of path-elements and calculate the interpolated value used by the path.
回答2:
Just access the bound data as you would in any other handler function:
function mousemoved(d,i) {
// do something with d and i
}
来源:https://stackoverflow.com/questions/29342670/d3-js-how-to-create-the-pop-up-event-when-moving-mouse-on-the-svg