當您進入繪圖區並顯示該點的工具提示時,您可能希望找到與鼠標最近的點。
我建議你閱讀this great post,這很好地解釋了你如何生成出色的工具提示。 上面的帖子並未顯示任何文字,但邏輯與你想要做的完全相同。關鍵的一段代碼是:
// append the rectangle to capture mouse
svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all")
.on("mouseover", function() { focus.style("display", null); })
.on("mouseout", function() { focus.style("display", "none"); })
.on("mousemove", mousemove);
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;
//you may want to change that to select a text area rather than a circle - whatever object is your tooltip in your code
focus.select("circle.y")
.attr("transform",
"translate(" + x(d.date) + "," +
y(d.close) + ")");
}