svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("Value"); svg.append("path") .datum(data) .attr("class", "line") .attr("d", line); var focus = svg.append("g") .attr("class", "focus") .style("display", "none"); focus.append("circle") .attr("r", 4.5); var rect = focus.append("rect") .attr("x", 9) .attr("dy", ".35em") .attr("width", 50) .attr("height", 50) .attr("fill", "yellow"); ... 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; focus.attr("transform", "translate(" + x(d.index_date) + "," + y(d.value) + ")"); rect.select("text").text(formatCurrency(d.value)); }
https://jsfiddle.net/xx77tzn3/9/
<svg> 的(相当不直观)不允许您附加 text 元素到 rect
<svg>
text
rect
//var text = focus.append("text")
并评论:
var text = rect.append("text")
然后单击鼠标功能,将第113行更改为:
focus.select("text").text(formatCurrency(d.value));
<g> .
<g>
编辑 :为了格式化要 矩形 ,您需要使文本的坐标相对于 <g> ,而不是 .即:
矩形
var text = focus.append("text") //var text = rect.append("text") .attr("x", 10) .attr("y", 10);
在矩形的顶部。
Updated js.fiddle